[英]Display file from Firebase Storage in Flutter
我找不到關於這個主題的任何內容,所以這是我的問題:
如何在Flutter中顯示Firebase存儲的文件?
到目前為止,這是我的 function:
PlatformFile? pickedFile;
Future uploadDoc() async {
final result = await FilePicker.platform.pickFiles(
allowMultiple: false,
type: FileType.custom,
allowedExtensions: ['pdf', 'jpg', 'png', 'jpeg'],
);
if (result != null) {
setState(() {
pickedFile = result.files.first;
});
} else {
return null;
}
if (pickedFile != null) {
final destination = 'files/';
final file = File(pickedFile!.path!);
Reference ref =
FirebaseStorage.instance.ref(destination).child(pickedFile!.name);
await ref.putFile(file);
String url = await ref.getDownloadURL();
print('$url is UPLOADED');
}
}
此時,文件已上傳到存儲中。 我可以獲得它的 URL 並使用 FutureBuilder 顯示它的名稱:
futureFiles = storage.ref('files/').listAll();
FutureBuilder<ListResult>(
future: futureFiles,
builder: (BuildContext context, snapshot) {
if (snapshot.hasError) {
return const Text('Something went wrong');
} else if (snapshot.connectionState == ConnectionState.waiting ||
!snapshot.hasData) {
return Center(
child: CircularProgressIndicator.adaptive(
backgroundColor: Colors.white,
),
);
} else {
final files = snapshot.data!.items;
return ListView.builder(
itemCount: files.length,
itemBuilder: ((context, index) {
final file = files[index];
return ListTile(
title: Text(file.name),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(Icons.launch),
color: Colors.blue,
onPressed: () {
// FUNCTION TO DISPLAY THE FILE
},
),
);
})),
],
);
}
},
),
列出了上傳的文件名,但如何顯示文件本身?
我認為正確的方法應該是訪問文件的 URL,但我不知道如何訪問。 有什么建議么?
getDownloadURL()
將為您提供該圖像的 a.network url,在您的示例中,您已經將其保存為:
String url = await ref.getDownloadURL();
您可以簡單地將 URL 分配給Image.network()
小部件以顯示它:
Image.network(url), // will show the image
要在Flutter中顯示Firebase Storage中的文件,可以使用FlutterWebviewPlugin package加載webview中的文件URL。
首先,您需要將FlutterWebviewPlugin
package 添加到您的 pubspec.yaml 文件中:
dependencies: flutter_webview_plugin: ^0.3.11
然后,您可以使用以下代碼在 webview 中加載文件 URL:
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
class MyWebView extends StatefulWidget {
final String fileUrl;
MyWebView({Key key, this.fileUrl}) : super(key: key);
@override
_MyWebViewState createState() => _MyWebViewState();
}
class _MyWebViewState extends State<MyWebView> {
@override
Widget build(BuildContext context) {
return WebviewScaffold(
url: widget.fileUrl,
withZoom: true,
withLocalStorage: true,
hidden: true,
initialChild: Container(
color: Colors.white,
child: Center(
child: CircularProgressIndicator(),
),
),
);
}
}
然后,您可以調用 MyWebView 小部件並將文件 URL 傳遞給它。 例如:
MyWebView(fileUrl: url),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.