从 Firebase 存储中获取所有图像

时间:2020-12-28 10:31:58

标签: firebase flutter firebase-storage

我想获取我所有的 Firebase 存储图像并显示它们。我确实在这里使用了 ...ref().child("").listAll() 方法,可以获取存储中的图像路径打印它们但不知道如何显示它们。请尽快帮助我,因为我的 Firebase 测试持续时间将于明天结束。

我的作品有一个重要的更新,所以我进行了编辑。我可以一一获取所有存储图像的下载地址,但无法在屏幕上列出它们。

import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:flutter/material.dart';

class StorageAlbumDisplay extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return StorageAlbumDisplayState();
  }
}

class StorageAlbumDisplayState extends State<StorageAlbumDisplay> {
  String _text;

  @override
  void initState() {
    super.initState();
    getImages();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("ALBUM DİSPLAY PAGE"),
      ),
      body: Container(
        child: Column(
          children: [
            RaisedButton(
                child: Text("Get Images"),
                onPressed: () {
                  getImages();
                }),
            Flexible(
              child: GridView.builder(
                  shrinkWrap: true,
                  itemCount: 10,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2),
                  itemBuilder: (context, index) {
                    return GridTile(
                      child: Center(child: Text(_text),),
                    );
                  }),
            ),
          ],
        ),
      ),
    );
  }

   void getImages() async {
    final firebase_storage.ListResult result = await firebase_storage
        .FirebaseStorage.instance
        .ref()
        .child("deneme")
        .child("resimler")
        .listAll();
    //result.items.forEach((firebase_storage.Reference ref) {
      //debugPrint("found file: ${ref.name}");
    //});

    //debugPrint("resultın ilk elemanı adı: " + result.items[1].name.toString());

    await firebase_storage.FirebaseStorage.instance
        .ref()
        .child("deneme")
        .child("resimler")
        .child(result.items[1].name.toString())
        .getData();
    var url = await firebase_storage.FirebaseStorage.instance
        .ref()
        .child("deneme")
        .child("resimler")
        .child(result.items[1].name.toString())
        .getDownloadURL();

    debugPrint("ilk resim urli: " + url.toString());

    final _text= url.toString();
    setState(() {    });
    debugPrint("text: "+ _text);

    
  }

}


这是我得到的控制台输出和错误:

Performing hot reload...
Syncing files to device SNE LX1...

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building:
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'

When the exception was thrown, this was the stack: 
#2      new Text (package:flutter/src/widgets/text.dart:370:10)
#3      StorageAlbumDisplayState.build.<anonymous closure> (package:firebase/StorageAlbumDisplay.dart:43:44)
#4      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:449:22)
#5      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1130:28)
#6      SliverMultiBoxAdaptorElement.performRebuild.processElement (package:flutter/src/widgets/sliver.dart:1076:66)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════
Reloaded 7 of 663 libraries in 2.441ms.
W/meb.firebase(24891): Accessing hidden method Lsun/misc/Unsafe;->getInt(Ljava/lang/Object;J)I (greylist, linking, allowed)
W/meb.firebase(24891): Accessing hidden method Lsun/misc/Unsafe;->putObject(Ljava/lang/Object;JLjava/lang/Object;)V (greylist, linking, allowed)
W/meb.firebase(24891): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed)
W/meb.firebase(24891): Accessing hidden method Lsun/misc/Unsafe;->getInt(Ljava/lang/Object;J)I (greylist, linking, allowed)

这是我按下“获取图像”按钮后的控制台输出,您可以看到图像的 url 为:

W/meb.firebase(24891): Accessing hidden method Lsun/misc/Unsafe;->getInt(Ljava/lang/Object;J)I (greylist, linking, allowed)
W/meb.firebase(24891): Accessing hidden method Lsun/misc/Unsafe;->putObject(Ljava/lang/Object;JLjava/lang/Object;)V (greylist, linking, allowed)
W/meb.firebase(24891): Accessing hidden method Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V (greylist, linking, allowed)
V/AudioManager(24891): querySoundEffectsEnabled...
I/flutter (24891): the pic url: https://firebasestorage.googleapis.com/v0/b/kalfa-firebase-projem.appspot.com/o/deneme%2Fresimler%2Fisim1608375656296?alt=media&token=b0ce2662-b668-4832-af20-0e9a20cf5446
I/flutter (24891): text: https://firebasestorage.googleapis.com/v0/b/kalfa-firebase-projem.appspot.com/o/deneme%2Fresimler%2Fisim1608375656296?alt=media&token=b0ce2662-b668-4832-af20-0e9a20cf5446

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building:
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'

When the exception was thrown, this was the stack: 
#2      new Text (package:flutter/src/widgets/text.dart:370:10)
#3      StorageAlbumDisplayState.build.<anonymous closure> (package:firebase/StorageAlbumDisplay.dart:43:44)
#4      SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:449:22)
#5      SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1130:28)
#6      SliverMultiBoxAdaptorElement.performRebuild.processElement (package:flutter/src/widgets/sliver.dart:1076:66)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 370 pos 10: 'data != null'
════════════════════════════════════════════════════════════════════════════════════════════════════

1 个答案:

答案 0 :(得分:0)

最后我解决了我的问题,只是遇到了一个我无法找出原因的简单错误。正如@asifali 和@mukul 所说,如果没有 getDowloadUrl,我就无法做到。在我使用 ...listAll().then(...)... 获取存储的图像名称和 getDownloadUrls 后,我确实将它们放入我的 FirebaseFirestore 集合并使用 Image.network("urlOfImages") 获取所有图像。这是我得到的解决方案代码、控制台输出和错误。如果你能帮助我解决这个新错误,我会很高兴。

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;

import 'package:flutter/material.dart';

class StorageAlbumDisplay extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return StorageAlbumDisplayState();
  }
}

class StorageAlbumDisplayState extends State<StorageAlbumDisplay> {


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("ALBUM DİSPLAY PAGE"),
      ),
      body: StreamBuilder(
          stream: FirebaseFirestore.instance.collection("storage_images").snapshots(),
          builder: (context, snapshot) {
            final querySnapshot = snapshot.data;
            return Container(
              child: Column(
                children: [
                  RaisedButton(
                      child: Text("Get Images"),
                      onPressed: () {
                        getImages();
                      }),
                  Flexible(
                    child: GridView.builder(
                        shrinkWrap: true,
                        itemCount: 10,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2),
                        itemBuilder: (context, index) {
                          final map = querySnapshot.docs[index].data();
                          return GridTile(
                            child: Image.network(map["url"]),
                          );
                        }),
                  ),
                ],
              ),
            );
          }
      ),
    );
  }

  void getImages() async {
    for(int i=0; i<10; i++){

      final _resultName  = await firebase_storage
          .FirebaseStorage.instance
          .ref()
          .child("deneme")
          .child("resimler")
          .listAll().then((value) => value.items[i].name);
      String resultName = _resultName.toString();
      debugPrint("resultın ${i+1}. elemanının adı: " + resultName);
      
      final _resultUrl  = await firebase_storage
        .FirebaseStorage.instance
        .ref()
        .child("deneme")
        .child("resimler")
        .listAll().then((value) => value.items[i].getDownloadURL());
      String resultUrl = _resultUrl.toString();
      debugPrint("resultın ${i+1}. elemanının urli: " + resultUrl);

      await FirebaseFirestore.instance.collection("storage_images").add({
        "name": resultName, "url": resultUrl
      });
    }


  }
}

控制台输出和错误:

Performing hot restart...
Syncing files to device SNE LX1...
Restarted application in 2.856ms.
W/meb.firebase(10713): Accessing hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J (greylist,core-platform-api, linking, allowed)
V/AudioManager(10713): querySoundEffectsEnabled...
W/DynamiteModule(10713): Local module descriptor class for providerinstaller not found.
D/ConnectivityManager(10713): requestNetwork and the calling app is: meb.firebase
I/DynamiteModule(10713): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(10713): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
D/ConnectivityManager(10713): requestNetwork and the calling app is: meb.firebase
V/AudioManager(10713): querySoundEffectsEnabled...
W/meb.firebase(10713): Accessing hidden method Lsun/misc/Unsafe;->getObject(Ljava/lang/Object;J)Ljava/lang/Object; (greylist, linking, allowed)
W/meb.firebase(10713): Accessing hidden method Lsun/misc/Unsafe;->getObject(Ljava/lang/Object;J)Ljava/lang/Object; (greylist, linking, allowed)

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#eb94f):
The getter 'size' was called on null.
Receiver: null
Tried calling: size

The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot> file:///C:/ornekler/firebase/flutter_app/firebase/lib/StorageAlbumDisplay.dart:23:13
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      StorageAlbumDisplayState.build.<anonymous closure> (package:firebase/StorageAlbumDisplay.dart:38:50)
#2      StreamBuilder.build (package:flutter/src/widgets/async.dart:525:81)
#3      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:129:48)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4744:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

还有一件事:如果我想用 FutureBuilder 而不是 Streambuilder 来做这件事,我会得到一个未来的错误。如果有人用 FutureBuilder 做到这一点,我也会很高兴。感谢您的帮助。