为什么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
。 (网络浏览器冻结了!)sleep
函数在指定的时间内暂停代码的执行,有效地阻塞了UI线程,它导致了问题。
您可以尝试使用
Future.delayed
而不是 sleep
。
await Future.delayed(Duration(milliseconds: 100)); // Simulate process without blocking UI