美文网首页
flutter 线程

flutter 线程

作者: 司徒新新 | 来源:发表于2022-11-04 13:28 被阅读0次

两种方法 一种自己开启isolate线程,一种是使用flutter给封装好的compute方法

第一种

//yaml内导入
isolate: ^2.0.2
//开启线程数量  进行负载均衡
Future<LoadBalancer> loadBalancer = LoadBalancer.create(5, IsolateRunner.spawn);

//要实行的方法
Future<int> useLoadBalancer(model) async {
  final lb = await loadBalancer;
  int res = await lb.run<int, int>(selectedPlayerHandel(model), 1);
  return res;
}

//必须是顶层方法 或者 静态方法
selectedPlayerHandel(model) {
  GameAudioPlayerUtil.resetPlayer();
  GameAudioPlayerUtil.playerHandle(model: model ?? GameMusicModel());
}

compute使用
要使用compute,必须注意的有两点,一是我们的compute中运行的函数,必须是顶级函数或者是static函数,二是compute传参,只能传递一个参数,返回值也只有一个,我们先看看本例中的compute优化吧:

真的很简单,只用在使用的时候,放到compute函数中就行了。

var res = await compute(
    selectedPlayerHandel(
        gameMusicList[selectedMusic] ?? GameMusicModel()),
    'selectedPlayerHandel');

如果发现有问题,请及时联系我,避免误人子弟...感谢!

相关文章

网友评论

      本文标题:flutter 线程

      本文链接:https://www.haomeiwen.com/subject/tvdptdtx.html