在Dartpad中调用sleep函数出现Script error问题咨询
Hey there, let's break down what's happening with your code in DartPad and get it working right. That vague "Script error." message is actually a clue that you're trying to use a part of Dart that doesn't play nice with the browser environment DartPad runs on.
The Root Cause
Your code imports dart:io and uses the sleep() function—but here's the key detail: dart:io is a native-only library. It's built for Dart apps running on desktop, servers, or mobile (via Flutter), where it can access system-level input/output tools. Browsers operate in a sandboxed environment that doesn't allow access to those system functions, so when DartPad tries to run sleep() in the browser, it throws an error.
The Fix: Use Web-Friendly Asynchronous Delay
Instead of blocking the thread with sleep(), you'll want to use Dart's asynchronous Future.delayed()—this tool is designed to work everywhere, including browsers and DartPad. Here's your rewritten code:
void main() async { await Future.delayed(const Duration(seconds: 1)); // Add any code you want to run after the delay here print("1 second has passed!"); }
A couple quick notes to explain the changes:
- We mark
main()asasyncbecause we're usingawaitto pause execution until the delay finishes. Future.delayed()doesn't block the event loop, which is critical for keeping web apps responsive (and plays perfectly with DartPad's environment).
内容的提问来源于stack exchange,提问作者Chris G.

