带有 Firebase 实时数据库和 futurebuilder 的 Gridview.builder

use*_*201 0 firebase firebase-realtime-database flutter google-cloud-firestore flutter-layout

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

Error: flutter: The following NoSuchMethodError was thrown building:
flutter: Class 'DataSnapshot' has no instance method '[]'.
flutter: Receiver: Instance of 'DataSnapshot'
Run Code Online (Sandbox Code Playgroud)

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

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();
              }
            }));
  }
}
Run Code Online (Sandbox Code Playgroud)

use*_*201 6

我可以用下面的代码解决它。再次,我不得不说 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();
                }
              })),
Run Code Online (Sandbox Code Playgroud)