[英]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.