Flutter中的isolate-spawn(一)

在Dart中一般来说是单线程模型,但是也可以开启新的线程,两个线程之间数据不共享,内存隔离,这个跟Java这些代码有些区别,对于耗时比较严重的逻辑,比如几百毫秒的逻辑,使用isolate比较适合,本文只做简单的使用演示,代码如下:
注意: Isolate.spawnUri 函数在Flutter中使用会出现以下错误:

[ERROR:flutter/runtime/dart_isolate.cc(882)] Unhandled exception:
UI actions are only available on root isolate.
import 'package:flutter/material.dart';
import 'dart:isolate';
import 'dart:async';
var isolate;
// isolate入口函数,该函数必须是静态的或顶级函数,不能是匿名内部函数。
void isolateSendPort(SendPort sendPort) {//这里面可以不停的发消息,只要线程没结束
  int counter = 0;
  sendPort.send("发送计数:$counter");
  isolate.kill(priority: Isolate.immediate);//杀死Isolate,发完消息后就杀死isolate线程
}
void main() async{//不放在Dart中执行是因为,主程序运行完就直接挂了,所以没法验证
  final receiver = ReceivePort();//接收端端口
  receiver.listen((message) {//端口监听
    print( "Main: 接收的内容 $message");
  });
  isolate = await Isolate.spawn(isolateSendPort, receiver.sendPort);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
  @override
  void dispose() {
    super.dispose();
    // isolate.kill(priority: Isolate.immediate);//杀死Isolate
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: Center(
          child: Container(
            child: Text('Hello World'),
          ),
        ),
      ),
    );
  }
}

参考链接:

  1. Dart中的Isolate: https://blog.csdn.net/joye123/article/details/102913497
  2. Dart 语言异步编程之Isolate:https://cloud.tencent.com/developer/article/1507841

你可能感兴趣的:(flutter)