新开线程来实现
import 'dart:async';
import 'dart:isolate';
void backgroundTask(SendPort sendPort) {
Timer.periodic(Duration(seconds: 5), (Timer t) {
print("Background task is running...");
sendPort.send("Background task is running...");
});
}
void main() async {
ReceivePort mainReceivePort = ReceivePort();
await Isolate.spawn(backgroundTask, mainReceivePort.sendPort);
mainReceivePort.listen((message) {
print("Received message from background task: $message");
});
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(''),
),
body: Center(
child: Text(''),
),
),
);
}
}