Flutter 上傳檔案和儲存在應用程式存儲目錄
原文 https://genotechies.medium.com/flutter-upload-file-and-save-in-application-storage-directory-4f1380b94e8a
前言
圖檔: Flutter 上傳檔案和儲存在應用程式存儲目錄
我寫這些文章是為了與你分享我的知識。Flutter 是軟體開發中最突出和最新興的技術,Google 通過添加重要的特性來維護 Flutter。版本經常更新。是以,Flutter 必須更新這些新功能。請通過可靠的來源,并研究他們。它們将有助于你以後的發展。這樣你才能活下去。
我看過許多教程,可以參考上傳檔案。但是找到一種适當的方法來上傳和儲存應用程式目錄中的檔案是很少見的。這裡是我的第 61 個 Flutter 教程,向您展示了我們如何使用圖像選擇器包上傳檔案,然後我們如何可以儲存在應用程式目錄中。
這在許多用例中都很有用。我在開發利用 SQLite 資料庫的脫機應用程式時使用了這個特性。首先,我嘗試将圖像儲存為 String。它成功了,但是在擷取資料時行的大小很大。正因為如此,它抛出了一個錯誤,我們嘗試了另一種方法。我們可以上傳圖像并将其儲存在應用程式目錄中。然後在我的示例中,我将複制的檔案路徑儲存在本地資料庫中,并擷取它來加載 Image。這就是解決辦法。我找到了自己的方式,也許還有其他的方法。以下是您需要遵循的步驟。
正文
建立一個新的 Flutter 項目
我從零開始。是以首先,我建立了一個新的 Flutter 項目。
實作 UI
我實作這個簡單的使用者界面隻是為了顯示功能。
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
getImage();
},
),
const SizedBox(height: 5),
buildimage(),
],
),
),
圖檔: 初始 UI 實作
添加軟體包
将 image_picker 和 path_Provider 包添加到 pubspec.yaml
image_picker: ^0.8.5+3
path_provider: ^2.0.11
上傳圖檔
單擊上載按鈕時,下面的方法将調用。
WWidget buildimage() => _image;
Future getImage() async{
// Pick the image from gallery
final pickedFile=await ImagePicker().pickImage(
source:ImageSource.gallery);
// Get the application folder directory
final directory=await getExternalStorageDirectory();
// Copy Image to the directory
if(pickedFile!=null){
if(directory!=null){
img=await File(pickedFile.path).copy(
'${directory.path}/${pickedFile.name}');
}
}
}
Image: 将檔案儲存在應用程式存儲目錄中
使用路徑值加載 Image
這是您可以使用儲存的檔案的地方。我設定了狀态并将 Image 作為 Image.file 加載。
setState(() {
if (pickedFile != null) {
if (directory != null) {
_image = Image.file(
img!,
height: MediaQuery
.of(context)
.size
.height / 5,
);
}else{
imageFile = File(pickedFile.path);
_image = Image.file(
imageFile!,
height: MediaQuery
.of(context)
.size
.height / 5,
);
print('image selected. ${imageFile.toString()}');
}
} else {
print('No image selected.');
}
});
Image: 使用檔案路徑加載檔案
結束語
如果本文對你有幫助,請轉發讓更多的朋友閱讀。
也許這個操作隻要你 3 秒鐘,對我來說是一個激勵,感謝。
祝你有一個美好的一天~
© 貓哥
- wx ducafecat
- https://wiki.ducafecat.tech