Flutter:从网络保存和加载图像

Flutter: Saving and loading Images from the newtwork

我们尝试在用户离线时保存、加载和显示来自网络的图像

  void saveImage(String imageUrl, String imageName) async{
    File file = File(await getImagePath(mediaName));
    ByteData questionMediaData = await NetworkAssetBundle(Uri.parse(imageUrl)).load("");
    file.writeAsString(questionMediaData.buffer.asUint8List());
  }

  Future<Uint8List> loadImage(String mediaName) async{
    String path = imageUrl + mediaName;
    if(await File(path).exists()){
      File file = File(await getImagePath(path));
      return await file.readAsString();
    }
    return null;
  }

  Future<String> getImagePath(String imageName) async {
    Directory appDocumentsDirectory = await getApplicationDocumentsDirectory(); 
    String appDocumentsPath = appDocumentsDirectory.path;
    String filePath = '$appDocumentsPath/$imageName';
    return filePath;
  }

我们有一个 ImageProvider-Class:

    class OurImageProvider {

  static Widget getImage(String imageName, {BoxFit fit = BoxFit.cover, double width, double height, ImageType imageType = ImageType.standard}) {

    if(!hasText(imageName)){
      if(imageType == ImageType.content)
        return Image(
            image: AssetImage('assets/dummy_images/catalog_dummy.jpg'),
            fit: BoxFit.cover,
            width: width,
            height: height,
        );
      else
        return Container();
    }


    return Image.network(imageName, fit: fit, width: width, height: height,
      errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
        return getAltImage(imageName, width, height, fit);
      },

    );
  }

  static Image getDummyImage(double width, double height, BoxFit fit) => Image(image: AssetImage('assets/dummy_images/dummy.jpg'), width: width, height: height, fit: fit);

  static getAltImage(String imageName, double width, double height, BoxFit fit) async{
      var localImage = await LocalStorage.instance.loadImage(imageName);
      if(localImage != null){
        return Image.memory(localImage, fit: BoxFit.cover,width: width, height: height, errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
          return getDummyImage(width, height, fit);
        },);
      }
      return getDummyImage(width, height, fit);
    }
}

我们现在的问题是,我找不到解决此问题的方法 class,因为 getAltImage 必须是异步的,我无法让 getImage 工作以用作构建方法中的子项...

尝试添加await:

return Image.memory(await localImage,...);

FutureBuilder 是我的解决方案...

    return Image.network(url, fit: fit, width: width, height: height,
  errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
    return FutureBuilder(
      future: getAltImage(imageName, width, height, fit),
      builder: (context, snapshot){
        if(snapshot.hasData){
          print(snapshot.data.toString());
          return snapshot.data;
        }else{
          return Container();
        }
      }
    );
  },