Gridview.builder与Firebase实时数据库和futurebuilder

问题描述 投票:0回答:1

来自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个回答
2
投票

我可以使用以下代码解决它。同样,我不得不说Firebase文档确实缺乏,这非常令人失望,因为Firebase是一个很棒的工具。此外,我不明白,没有关于“如何使用Firebase with 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();
                }
              })),
© www.soinside.com 2019 - 2024. All rights reserved.