当前位置: 首页 > news >正文

Flutter Isolate解决耗时任务导致卡死

先来对比一下在Flutter的ui主线程下直接计算一个耗时任务的情况:

import 'package:flutter/material.dart';void main() {runApp(const MaterialApp(home: H(),));
}class H extends StatefulWidget {const H({super.key});@overrideState<H> createState() => _HState();
}class _HState extends State<H> {int _count = 0;@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text("耗时计算"),),body: Center(child: Text("$_count"),),floatingActionButton: FloatingActionButton(child: const Text("start"),onPressed: () {_count = countPrimes(100000000);setState(() {});}),);}
}// 计算质数个数
int countPrimes(int n) {List<bool> isPrime = List.filled(n + 1, true);isPrime[0] = isPrime[1] = false;for (int i = 2; i * i <= n; i++) {if (isPrime[i]) {for (int j = i * i; j <= n; j += i) {isPrime[j] = false;}}}return isPrime.where((prime) => prime).length;
}

发现点击按钮后,直接卡死,现在换成异步执行:

import 'package:flutter/material.dart';void main() {runApp(const MaterialApp(home: H(),));
}class H extends StatefulWidget {const H({super.key});@overrideState<H> createState() => _HState();
}class _HState extends State<H> {int _count = 0;@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text("耗时计算"),),body: Center(child: Text("$_count"),),floatingActionButton: FloatingActionButton(child: const Text("start"),onPressed: () async {_count = await countPrimes(100000000);setState(() {});}),);}
}// 计算质数个数
Future<int> countPrimes(int n) async {List<bool> isPrime = List.filled(n + 1, true);isPrime[0] = isPrime[1] = false;for (int i = 2; i * i <= n; i++) {if (isPrime[i]) {for (int j = i * i; j <= n; j += i) {isPrime[j] = false;}}}return isPrime.where((prime) => prime).length;
}

发现仍旧会卡死,因为计算过程还是发生在ui线程中,现在使用isolate进行对比:

import 'dart:isolate';import 'package:flutter/material.dart';void main() {runApp(const MaterialApp(home: H(),));
}class H extends StatefulWidget {const H({super.key});@overrideState<H> createState() => _HState();
}class _HState extends State<H> {int _count = 0;ReceivePort? _receivePort;@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text("耗时计算"),),body: Center(child: Text("$_count"),),floatingActionButton: FloatingActionButton(child: const Text("start"),onPressed: () {_receivePort = ReceivePort();Isolate.spawn(countPrimes, [100000000, _receivePort!.sendPort]);_receivePort!.listen((message) {setState(() {_count = message;});});}),);}
}// 计算质数个数
void countPrimes(List<dynamic> args) {int n = args[0];SendPort sendPort = args[1];List<bool> isPrime = List.filled(n + 1, true);isPrime[0] = isPrime[1] = false;for (int i = 2; i * i <= n; i++) {if (isPrime[i]) {for (int j = i * i; j <= n; j += i) {isPrime[j] = false;}}}sendPort.send(isPrime.where((prime) => prime).length);
}

发现问题得到解决

http://www.lryc.cn/news/532945.html

相关文章:

  • 使用deepseek快速创作ppt
  • STM32的HAL库开发---高级定时器---输出比较模式实验
  • python Excel 表读取合并单元格以及清除空格符
  • 额外题目汇总2-链表
  • C#控件开发6—指示灯
  • 探索从传统检索增强生成(RAG)到缓存增强生成(CAG)的转变
  • 【学习总结|DAY036】Vue工程化+ElementPlus
  • 【GitHub】GitHub 2FA 双因素认证 ( 使用 Microsoft Authenticator 应用进行二次验证 )
  • c# 2025/2/7 周五
  • 蓝桥杯思维训练(五)
  • I.MX6ULL 中断介绍下
  • Elasticsearch 生产集群部署终极方案
  • Python用langchain、OpenAI大语言模型LLM情感分析苹果股票新闻数据及提示工程优化应用...
  • 【正点原子K210连载】第六十七章 音频FFT实验 摘自【正点原子】DNK210使用指南-CanMV版指南
  • Centos Ollama + Deepseek-r1+Chatbox运行环境搭建
  • ReactNative进阶(五十九):存量 react-native 项目适配 HarmonyOS NEXT
  • go并发和并行
  • 一种解决SoC总线功能验证完备性的技术
  • Web3 与区块链:开启透明、安全的网络新时代
  • c#中Thread.Join()方法的经典示例
  • 深入了解越权漏洞:概念、危害与防范
  • MySQL 数据库编程-C++
  • dl学习笔记(9):pytorch数据处理的完整流程
  • wps中的vba开发
  • 力扣 LCR 078 合并K个升序链表
  • 【hive】记一次hiveserver内存溢出排查,线程池未正确关闭导致
  • React Native 开发 安卓项目构建工具Gradle的配置和使用
  • IntelliJ IDEA新版本的底部version control(或git)里local change窗口显示配置修改详细教程
  • MySQL三大日志——binlog、redoLog、undoLog详解
  • MCU应用踩坑笔记(ADC 中断 / 查询法)