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);
}

发现问题得到解决

相关推荐
浮生若茶808812 小时前
Flutter环境搭建全攻略之-Macos环境搭建
flutter·macos
农夫三拳_有点甜17 小时前
Flutter Expanded 组件总结
flutter
火柴就是我18 小时前
跟着官方demo 学flame 之 word 坐标系以及Camera的一些属性
flutter
新镜19 小时前
【Flutter】drag_select_grid_view: ^0.6.2 使用
flutter
程序员老刘19 小时前
Google突然“变脸“,2026年要给全球开发者上“紧箍咒“?
android·flutter·客户端
鹏多多.1 天前
flutter-使用fluttertoast制作丰富的高颜值toast
android·前端·flutter·ios
新镜2 天前
【Flutter】RefreshIndicator 无法下拉刷新问题
flutter
星秋Eliot2 天前
Flutter的三棵树
前端·flutter
humiaor2 天前
Flutter之riverpod状态管理Widget UI详解
flutter·consumer·widget·hooks·provider·riverpod·hookwidget
农夫三拳_有点甜2 天前
Flutter Stack 组件总结
flutter