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

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

Dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    home: H(),
  ));
}

class H extends StatefulWidget {
  const H({super.key});

  @override
  State<H> createState() => _HState();
}

class _HState extends State<H> {
  int _count = 0;

  @override
  Widget 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;
}

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

Dart 复制代码
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    home: H(),
  ));
}

class H extends StatefulWidget {
  const H({super.key});

  @override
  State<H> createState() => _HState();
}

class _HState extends State<H> {
  int _count = 0;

  @override
  Widget 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进行对比:

Dart 复制代码
import 'dart:isolate';

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    home: H(),
  ));
}

class H extends StatefulWidget {
  const H({super.key});

  @override
  State<H> createState() => _HState();
}

class _HState extends State<H> {
  int _count = 0;
  ReceivePort? _receivePort;

  @override
  Widget 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);
}

发现问题得到解决

相关推荐
明似水4 小时前
Flutter 弹窗队列管理:支持优先级的线程安全通用弹窗队列系统
javascript·安全·flutter
坚果的博客11 小时前
坚果派已适配的鸿蒙版flutter库【持续更新】
flutter·华为·开源·harmonyos
ak啊16 小时前
Flutter项目架构设计方案
flutter
JarvanMo18 小时前
在Dart泛型中应该优先使用dynamic还是Object?
前端·flutter·dart
恋猫de小郭19 小时前
Flutter 在 Dart 3.8 开始支持 Null-Aware Elements 语法,自动识别集合里的空元素
android·前端·flutter
恋猫de小郭1 天前
Flutter Widget IDE 预览新进展,开始推进落地发布
android·前端·flutter
Ya-Jun1 天前
常用第三方库:flutter_boost混合开发
android·flutter·ios
技术蔡蔡1 天前
全面解读Flutter状态管理框架signals使用,知其然和所以然
flutter·dart
pengyu1 天前
【Flutter 状态管理 - 柒】 | InheritedWidget:藏在组件树里的"魔法"✨
android·flutter·dart
肥肥呀呀呀1 天前
flutter 小知识
flutter