flutter 保存网络图片至本地

首先需要配置
android\app\src\main\AndroidManifest.xml

//开启读写权限
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

库:

dio: ^4.0.0
flutter_cache_manager: ^3.1.2
permission_handler: ^8.1.4+1
image_gallery_saver: ^1.1.0

使用:

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:dio/dio.dart';

//保存到手机

String _imagePath =
      "https://www.callmysoft.com/static/index/images/image_dgital%20creativity.png";
  void _saveImg(dialogContext) async {
    if (await Permission.storage.request().isGranted) {
      var response = await Dio()
          .get(_imagePath, options: Options(responseType: ResponseType.bytes));
      final result =
          await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
      // print(result);
      if (result["isSuccess"]) {
        Navigator.pop(dialogContext);
        showToast("保存成功");
      } else {
        Navigator.pop(dialogContext);
        showToast("保存失败");
      }
    }
  }

await Permission.storage.request().isGranted
这句就能知道让用户选择是否开启访问权限

上一篇:Flutter垃圾回收器


下一篇:Dart异步任务