flutter-讀寫二進制文件到設備

看了下不少文章,本地文件存儲都只有存儲txt文件,咱們探索下存儲二進制文件吧。html

保存二進制文件到設備硬盤上。sql

咱們保存一個圖片到手機本地上,並讀取展現圖片到app上。
以百度logo圖爲例子api

寫入圖片

邏輯以下: 獲取本地路徑 -> 根據圖片url開始下載獲取到二進制文件 -> 圖片文件寫入到本地路徑緩存

寫入本地文件

寫入文件有幾種方式點我查看file文檔 分別是字符串和二進制,而寫入的時候分同步和異步,因此寫入的有4種。\bash

writeAsBytes這個函數名字,這廝須要 bytes

代碼
writeFile(String filePath, String imgUrl){
      File file = new File(filePath);
      if(!file.existsSync()) {
        file.createSync();
      }
      getRemoteFileStream(imgUrl, (fileInfo){
        if(fileInfo["ok"]){
          file.writeAsBytes(fileInfo["bytes"]);
        }else{
          debugPrint("異常");
        }
      });
    }
複製代碼

獲取遠程文件流

新建一個http鏈接,使用dartimport 'dart:io';自帶的哦。
使用Uri.parse解析完整的url
request.close()開始發送請求(小聲bb:這個命名一言難盡) 獲取到數據後,response是一個HttpClientResponse類型,而HttpClientResponse類型Stream的實現app

abstract class HttpClientResponse implements Stream<List<int>>
複製代碼

關於Stream提及來比較複雜,推薦一個文章傳送門 Stream最後會吐出List<int>,也就是咱們須要的Bytesless

代碼
// get文件流
    getRemoteFileStream(String url, cb) async{
      return new Future(() async{
        HttpClient httpClient = new HttpClient();
        HttpClientRequest request = await httpClient.getUrl(Uri.parse(url));
        HttpClientResponse response = await request.close();
        if (response.statusCode == HttpStatus.ok) {
          List<int> buffer = [];
          response.listen((data){
              data.forEach((e){
                buffer.add(e);
              });
            },
            onDone: (){
              cb({
                "ok": true,
                "bytes": buffer
              });
            },
            onError: (e){
              print(e);
            }
          );
        }else{
          debugPrint('HTTP request failed');
        }
      });
    }
複製代碼

寫好了上面兩個函數,咱們如今能夠獲取本地文件路徑來寫入圖片了異步

最後一步,執行寫入

獲取本地路徑分爲臨時文件文檔路徑 咱們使用path_provider來獲取本地路徑async

path_provider: ^1.4.0
import 'package:path_provider/path_provider.dart';
複製代碼

獲取本地路徑,執行讀寫本地文件ide

代碼
getLocalhostBooks() async{
    String imgUrl = 'https://user-gold-cdn.xitu.io/2019/11/1/16e24dc995c95343?w=540&h=258&f=png&s=7877';
    Directory tempDir = await getTemporaryDirectory();
    Directory appDocDir = await getApplicationDocumentsDirectory();
    debugPrint('本地路徑');
    debugPrint(tempDir.path);
    debugPrint(appDocDir.path);
    String testPath = '${appDocDir.path}/test.png';

    // // 寫入圖片
    // writeFile(testPath, imgUrl);
    // 讀取圖片
    readFile(testPath, imgUrl);
}
複製代碼

讀取

讀取本地文件

readFile(String filePath, String imgUrl) async{
      File file = new File(filePath);
      Uint8List fileBytes = await file.readAsBytes();
      setState(() {
        imgBytes =  fileBytes;
        print(imgBytes);
      });
    }
複製代碼

讀取比較簡單一點,獲取bytes,而後渲染就是了。

setState(() {
    imgBytes =  fileBytes;
    print(imgBytes);
});
複製代碼
Container(
    child: Image.memory(imgBytes, gaplessPlayback: true,),
)
複製代碼

效果

其餘

嘻嘻,利用上面的知識,就能夠手寫一個圖片緩存器了。

看懂了請點贊~~ 喵喵

下一篇,集合sqlite3實現本地書籍加入書架

相關連接

File文檔
獲取本地路徑文檔

相關文章
相關標籤/搜索