Search code examples
imageflutteriosaveloading

Flutter: Saving and loading Images from the newtwork


We try to save, load and display images from the network, when the user is offline

  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;
  }

We have an 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);
    }
}

Our Problem is now that I don't find a way to fix this class as getAltImage has to be async and I cannot get getImage working to be usable as a child in the build method...


Solution

  • Try to add await:

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