compute () ใน flutter ไม่มีผล
Sep 19 2020
ผมลองใช้computeใน Flutter ที่นี่ฉันพยายามส่งผ่านพารามิเตอร์หลายตัวในแผนที่ แต่รหัสในฟังก์ชันของฉันmyFunctionไม่ทำงาน ฉันไม่ได้รับข้อผิดพลาดหรืออย่างอื่น ดูเหมือนว่ารหัสของฉันจะถูกละเว้น คุณพบข้อผิดพลาดที่นี่หรือไม่?
ฟังก์ชัน Compute:
Map map = Map();
map['resultList'] = resultList;
map['_getImageFileFromAssets'] = _getImageFileFromAssets;
map["picturesData"] = picturesData;
map["albumID"] = albumID;
await compute(myFunction, map);
เรียกใช้ฟังก์ชันต่อไปนี้:
Future<bool> myFunction(map) async {
var resultList = map["resultList"];
var _getImageFileFromAssets = map["_getImageFileFromAssets"];
var picturesData = map["picturesData"];
var albumID = map["albumID"];
print("Starten");
for (var i = 0; i < resultList.length; i++) {
print(i);
File imageFile = await _getImageFileFromAssets(resultList[i]);
final appDir = await syspath.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage =
await File(imageFile.path).copy('${appDir.path}/$fileName');
// Creating thumbnails
final thumb = image.decodeImage(await File(savedImage.path).readAsBytes());
final thumbImage = image.copyResize(thumb, width: 500);
new File('${appDir.path}/$fileName-thumb-500.jpg')
.writeAsBytes(image.encodeJpg(thumbImage));
final finalThumbImage = File('${appDir.path}/$fileName-thumb-500.jpg');
picturesData.add(Picture(
album: albumID,
path: savedImage.path,
thumbPath: finalThumbImage.path,
timestamp: Timestamp.now()));
}
return true;
}
คำตอบ
kazume Sep 19 2020 at 11:30
โอเครหัส - ฉันใส่ไว้ในdartpad.dev :
import 'package:flutter/foundation.dart';
void main() {
Map map = Map();
compute(myFunction, map).then((result) => print(result));
}
Future<bool> myFunction(Map map) async {
print("Starten");
// fake long process
await Future.delayed(Duration(seconds: 5));
return true;
}
และรับสิ่งนี้เป็นผลลัพธ์คอนโซล:
Starten
true
นอกจากนี้: มีเหตุผลที่คุณต้องการให้พารามิเตอร์ "map" ในฟังก์ชันของคุณเป็นdynamicอย่างไร ถ้าไม่ฉันจะประกาศเป็นประเภทMap(เหมือนตอนนี้)