flutter의 compute ()는 효과가 없습니다.

Sep 19 2020

computeFlutter 에서 사용하려고합니다 . 여기서는 Map 내부에 여러 매개 변수를 전달하려고합니다. 하지만 내 기능의 코드가 작동 myFunction하지 않습니다. 오류나 다른 것이 없습니다. 내 코드가 무시되는 것 같습니다. 여기에 오류가 있습니까?

계산 기능 :

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지금처럼 유형으로 선언합니다 .