You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Dartpad中调用sleep函数出现Script error问题咨询

Why You're Getting "Script error." in DartPad & How to Fix It

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() as async because we're using await to 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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:44:12