Flutter非阻塞流程

问题描述 投票:0回答:1

为什么flutter无法处理非阻塞进程?
据我所知,生成的异步方法是为了处理这个概念。
例如这段代码:

import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:io';
import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              ElevatedButton(
                onPressed: processFile,
                child: Text("File Process"),
              ),
              SizedBox(width: 20),
              ElevatedButton(
                onPressed: anotherProcess,
                child: Text("Another Process"),
              )
            ],
          ),
        ),
      ),
    );
  }

  static Future<void> processFile() async {
    developer.log("File Process Executed");
    final selectedFile = await FilePicker.platform.pickFiles(allowMultiple: false, type: FileType.any);

    if (selectedFile == null) return;

    var fileBytes = selectedFile.files.single.bytes!;

    const chunkSize = 1024 * 1024;
    var totalSize = fileBytes.length;
    var totalChunks = (totalSize / chunkSize).ceil();

    developer.log("TotalSize:  $totalSize  TotalChunks: $totalChunks");

    final Uint8List byteData = Uint8List.fromList(fileBytes);
    final chunks = List<Uint8List>.generate(
      totalChunks,
      (int index) {
        final start = index * chunkSize;
        final end = start + chunkSize < totalSize ? start + chunkSize : totalSize;
        return byteData.sublist(start, end);
      },
    );

    for (int i = 0; i < chunks.length; i++) {
      var b64 = base64Encode(chunks[i]);
      sleep(Duration(milliseconds: 100)); // only for simulate process 
      developer.log("Process Chunk $i $b64");
    }
  }

  static Future<void> anotherProcess() async {
    developer.log("Another Process Executed");
  }
}

我有两种方法

processFile
anotherProcess
。 当我单击
File Process
按钮时,在文件处理完成之前无法调用
Another Process
。 (网络浏览器冻结了!)
我误解了异步函数?或者我的代码有问题?
注意:我在网络浏览器上测试了这段代码。 (我认为平台类型与异步概念无关)

flutter dart asynchronous
1个回答
0
投票

sleep
函数在指定的时间内暂停代码的执行,有效地阻塞了UI线程,它导致了问题。

您可以尝试使用

Future.delayed
而不是
sleep

await Future.delayed(Duration(milliseconds: 100)); // Simulate process without blocking UI
© www.soinside.com 2019 - 2024. All rights reserved.