Home > front end >  Display file from Firebase Storage in Flutter
Display file from Firebase Storage in Flutter

Time:12-28

I couldn't find anything on this subject so here's my question :

How to display a file from Firebase Storage in Flutter ?

So far, here's my 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');
    
    }
  }

At this point, the file is uploaded in storage. I can get its URL and display its name using a 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
                              },
                            ),
                      );
                    })),
              ],
            );
          }
        },
      ),

The uploaded files's name are listed, but how can I display the file itself ?

I think the right way should be to access the file's URL, but I don't know how. Any suggestions ?

CodePudding user response:

the getDownloadURL() will get you a network url of that image, in your example, you're already saving it as :

String url = await ref.getDownloadURL();

you can simply assign that URL to an Image.network() widget to show it:

Image.network(url), // will show the image

CodePudding user response:

To display the file from Firebase Storage in Flutter, you can use the FlutterWebviewPlugin package to load the file URL in a webview.

First, you will need to add the FlutterWebviewPlugin package to your pubspec.yaml file:

dependencies: flutter_webview_plugin: ^0.3.11

Then, you can use the following code to load the file URL in a webview:

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(),
        ),
      ),
    );
  }
}

Then, you can call the MyWebView widget and pass the file URL to it. For example:

MyWebView(fileUrl: url),
  • Related