簡體   English   中英

如何從網絡下載圖像並在 flutter 中離線用作資產圖像

[英]How to download image from network and use as an asset image offline in flutter

我正在使用sqlflite flutter package 為我的應用程序管理一個小型數據庫,有一個表,其中我有一些來自互聯網的圖像的 url,但我需要保存它們並使用文件而不是 url 稍后顯示這些圖像。 我的意思是我想做這樣的事情:

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

那么,有什么方法可以從 url 中獲取圖像並將其保存以便以后可以訪問它?

您可以使用NetworkAssetBundle下載圖像並轉換為 Unint8List

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

然后你可以通過Image.memory()小部件加載它

Image.memory(bytes);

您可以將該數據存儲在 sqflite 中並在需要時檢索

您可以使用 path_provider package 從互聯網下載並保存在本地。 然后,如果可用,您可以從本地資產加載。 否則它也可以從互聯網上下載。

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

}

您是否嘗試過https://pub.dev/packages/cached_network_image

看起來這個包將滿足您的要求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM