【问题标题】:Gridview.builder with Firebase realtime database and futurebuilder带有 Firebase 实时数据库和 futurebuilder 的 Gridview.builder
【发布时间】:2019-07-22 05:48:28
【问题描述】:

来自 Firestore,我有点挣扎如何从 Firebase 实时数据库接收数据。我只想要从实时数据库加载的图像的漂亮网格视图。

Error: flutter: The following NoSuchMethodError was thrown building:
flutter: Class 'DataSnapshot' has no instance method '[]'.
flutter: Receiver: Instance of 'DataSnapshot'

我猜它与索引有关。不知道如何在列表中正确映射它。

import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(16.0),
        child: new FutureBuilder(
            future: FirebaseDatabase.instance
                .reference()
                .child('messages')
                .child('1551276762582')
                .orderByChild('messagetype')
                .equalTo('1')
                .once(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                if (snapshot.data != null) {
                  return new Column(
                    children: <Widget>[
                      new Expanded(
                        child: new GridView.builder(
                          // itemCount: item.length,
                          gridDelegate:
                              new SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 2),
                          itemBuilder: (context, index) {
                            return GridTile(
                                child: CachedNetworkImage(
                                    imageUrl: snapshot.data[index]['imageUrl']
                                        .toString()));
                          },
                        ),
                      )
                    ],
                  );
                } else {
                  return new CircularProgressIndicator();
                }
              } else {
                return new CircularProgressIndicator();
              }
            }));
  }
}

【问题讨论】:

    标签: firebase firebase-realtime-database flutter google-cloud-firestore flutter-layout


    【解决方案1】:

    我可以用下面的代码解决它。再次,我不得不说 Firebase 文档确实缺乏,这非常令人失望,因为 Firebase 是一个很棒的工具。此外,我不明白,没有关于“如何将 Firebase 与 Flutter 一起使用”的文档(我们正在谈论这两种 Google 产品。)尽管如此,这里是任何喜欢将 Streambuilder 与 Gridview.builder 一起使用的人的工作代码使用 Flutter 中的实时数据库:

    StreamBuilder(
                  stream: FirebaseDatabase.instance
                      .reference()
                      .child('messages')
                      .child(groupId)
                      .orderByChild('messagetype')
                      .equalTo(1)
                      .onValue,
                  builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
                    if (snapshot.hasData) {
                      if (snapshot.data.snapshot.value != null) {
                        Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
                        List<dynamic> list = map.values.toList()
                          ..sort(
                              (a, b) => b['timestamp'].compareTo(a['timestamp']));
    
                        return GridView.builder(
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 3),
                          itemCount: list.length,
                          padding: EdgeInsets.all(2.0),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              child: GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => SecondScreen(
                                            imageUrl: list[index]["imageUrl"])),
                                  );
                                },
                                child: CachedNetworkImage(
                                  imageUrl: list[index]["imageUrl"],
                                  fit: BoxFit.cover,
                                ),
                              ),
                              padding: EdgeInsets.all(2.0),
                            );
                          },
                        );
                      } else {
                        return Container(
                            child: Center(
                                child: Text(
                          'Es wurden noch keine Fotos im Chat gepostet.',
                          style: TextStyle(fontSize: 20.0, color: Colors.grey),
                          textAlign: TextAlign.center,
                        )));
                      }
                    } else {
                      return CircularProgressIndicator();
                    }
                  })),
    

    【讨论】:

      【解决方案2】:

      帮助我解决问题的方法是通过以下方式将快照显式转换为地图。

      Map yourModel = Map.from(datasnapshot);
      

      在处理空数据等时,我也必须通过以下方式将来自未来 Builder 的 asyncSnap 值转换为来自 firebase 的 Datasnapshot

      Datasnapshot snap = asyncSnap.data;
      

      然后处理 snap 为 null

      if(snap.value!=null){}
      

      希望这会有所帮助!如果您需要帮助,请给我留言

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        • 2020-12-31
        • 2021-07-12
        • 2020-10-29
        • 1970-01-01
        相关资源
        最近更新 更多