How to download image from network and use as an asset image offline in flutter
Asked Answered
A

3

2

I am using sqlflite flutter package to manage a small database for my app, there is a table where I have some urls for few images from the internet , but I need to save them and use the files instead of urls to show this images later. I mean I want to do something like this :

bool internet
internet ? Image.network('the_url') : Image.assets("path to image in my assets folder")

so, is there any way to fetch images from urls and save it to be able to access it later?

Averett answered 27/2, 2020 at 14:36 Comment(0)
C
9

You can download the image with NetworkAssetBundle and convert to Unint8List

final ByteData imageData = await NetworkAssetBundle(Uri.parse("YOUR_URL")).load("");
final Uint8List bytes = imageData.buffer.asUint8List();

Then you can load it through Image.memory() widget

Image.memory(bytes);

You can store that data in sqflite and retrive when needed

Cordy answered 27/2, 2020 at 14:44 Comment(1)
Seems like not working for Flutter Web (3.0.5), error shows Unsupported operation: Platform._version. Any solution that will work on Flutter Web?Dachi
T
1

You can use the path_provider package to download from internet and save it locally. Then you can load from local asset if available. Otherwise it can download from the internet also.

  Future<String?> loadPath() async {
    var dir = await getApplicationDocumentsDirectory();
    String dirName = widget.url!.substring(87);
    file = File("${dir.path}/$dirName");

    if (file.existsSync() == true && _isDownloadingPDF == false) {
      // debugPrint('file.path returned');
      return file.path;
    } else {
      return null;
    }
  }
Thirteenth answered 3/9, 2022 at 8:26 Comment(0)
B
-2

Have you tried https://pub.dev/packages/cached_network_image?

It seems like this package will fulfil your requirements.

Blithering answered 7/9, 2020 at 12:8 Comment(1)
please be more specific and provide some code, explaining how this actually converts a network image to ImageGanger

© 2022 - 2025 — McMap. All rights reserved.