Var*_*rma 10 dart dart-isolates flutter
谁能告诉我这段代码有什么问题吗?
void onPressed() async {
//Navigator.pushNamed(context, "/screen2", arguments: []);
var receivePort = ReceivePort();
await Isolate.spawn(gotoNext, [receivePort.sendPort]);
final msg = await receivePort.first;
print(msg);
}
void gotoNext(List<dynamic> args) {
SendPort sendPort = args[0];
log(args.toString());
Isolate.exit(sendPort, "OK");
}
Run Code Online (Sandbox Code Playgroud)
E / flutter(12062):[错误:flutter/lib/ui/ui_dart_state.cc(209)]未处理的异常:无效参数:隔离消息中的非法参数:(对象扩展NativeWrapper - Library:'dart:ui'类:路径)
小智 22
Hii 您的代码中有一个错误。据我从官方文档了解到 Isolate 的回调方法应该是顶级函数或static方法。
所以这个问题有两种解决方案。
解决方案 1. 将回调函数声明为顶级函数。
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key? key, required this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: TextButton(
child: const Text("Run Isolate"),
onPressed: _onPressed,
));
);
}
// Callback function for Text Button Event this should be a class member
void _onPressed() async {
var receivePort = ReceivePort();
// Here runMyIsolate methos should be a top level function
await Isolate.spawn(runMyIsolate, [receivePort.sendPort, "My Custom Message"]);
print(await receivePort.first);
}
}
// We declare a top level function here for an isolated callback function
void runMyIsolate(List<dynamic> args) {
var sendPort = args[0] as SendPort;
print("In runMyIsolate ");
Isolate.exit(sendPort, args);
}
Run Code Online (Sandbox Code Playgroud)
解决方案 2. 相反,我们可以将此函数声明为
static同一类的函数,请考虑下面的示例。
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key? key, required this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: TextButton(
child: const Text("Run Isolate"),
onPressed: _onPressed,
));
);
}
// Callback function for Text Button Event this should be a class member
void _onPressed() async {
var receivePort = ReceivePort();
// Here runMyIsolate methos should be a top level function
await Isolate.spawn(runMyIsolate, [receivePort.sendPort, "My Custom Message"]);
print(await receivePort.first);
}
// We declare a static function here for an isolated callback function
static void runMyIsolate(List<dynamic> args) {
var sendPort = args[0] as SendPort;
print("In runMyIsolate ");
Isolate.exit(sendPort, args);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13916 次 |
| 最近记录: |