flutter 下載文件


android 

  1.在 android/app/app/src/main/AndroidManifest.xml 中添加讀取文件的權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  2. 下載方法

Future downloadFile({String url}) async {
  Dio dio = new Dio();
  String path = await getLocalStorage('serverPath');
  dio.options.baseUrl = path == null ? "http://192.168.1.170:8180/" : path;
  //設置連接超時時間
  dio.options.connectTimeout = 10000;
  //設置數據接收超時時間
  dio.options.receiveTimeout = 10000;
  Response response;
  try {
    response = await dio.download(url, "/storage/emulated/0/test.png");
    if (response.statusCode == 200) {
      print('下載請求成功');
    } else {
      throw Exception('接口出錯');
    }
  } catch (e) {
    showTotast('服務器出錯或網絡連接失敗!');
    return print('ERROR:======>$e');
  }
}

  3.  文件權限不僅需要需要在AndroidManifest中配置,還需要在使用前check是否真正擁有權限,以動態申請,否則會報錯的

     申請權限使用 permission_handler 組件,5.0版本 之前的寫法跟之后的寫法不一樣

 permission_handler: ^5.0.0 # 檢測權限,沒有權限就申請
 bool status = await Permission.storage.isGranted;
    //判斷如果還沒擁有讀寫權限就申請獲取權限
    if (!status) {
      return await Permission.storage.request().isGranted;
    } 
// 調用下載方法 --------做該做的事

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM