【问题标题】:Flutter Firestore readFlutter Firestore 读取
【发布时间】:2021-12-27 15:56:22
【问题描述】:

我想将这段从实时数据库读取的代码更改为 Firestore。 下面是从实时数据库中读取的代码:

 final dbRef = FirebaseDatabase.instance.reference().child("signals");
  List<Map<dynamic, dynamic>> lists = [];
  var lists;
  final formatter = intl.NumberFormat("#,##0.0######"); // for price change
  final percentageFormat = intl.NumberFormat("##0.0#"); // for price change
  final GlobalKey<ExpansionTileCardState> cardA = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color.fromRGBO(34, 44, 59, 1.0),

        body: Center(
          child: Column(

            children: [ SizedBox(
              height: 50.0,
            ),
              Image.asset(
                logoImage,
                fit: BoxFit.contain,
                color: Color.fromRGBO(251, 199, 0, 1.0),
                height: 100.0,
                width: 100.0,
              ),Text(
                '[users]',
                style: TextStyle(
                  fontSize: 20,
                  color: Color.fromRGBO(251, 199, 0, 1.0),
                ),
              ),
              FutureBuilder(
                  future: dbRef.orderByChild("type").equalTo("Free").once(),
                  builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
                    if (snapshot.hasData) {
                      lists.clear();
                      Map<dynamic, dynamic> values = snapshot.data.value;
                      values.forEach((key, values) {
                        lists.add(values);
                      });
                      return new ListView.builder(
                          shrinkWrap: true,
                          itemCount: lists.length,
                          itemBuilder: (BuildContext context, int index) {
                            Divider(
                              thickness: 1.0,
                              height: 1.0,
                            );
                            return ExpansionTileCard(
                              baseColor:  Color.fromRGBO(34, 44, 59, 1.0),
                              expandedColor: Color.fromRGBO(24, 31, 42, 1.0),

                              leading: CircleAvatar(
                                child: Image.asset("assets/images/giphyy.gif",), backgroundColor: Colors.transparent,),
                              title: Text(
                                lists[index]["coinname"].toString(),
                                style: TextStyle(
                                    color: Color.fromRGBO(251, 199, 0, 1.0)),
                              ),

                              children: <Widget>[
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                      horizontal: 16.0,
                                      vertical: 8.0,
                                    ),
                                    child: Text(lists[index]["signalinfo"].toString(),
                                      style: TextStyle(fontWeight: FontWeight.bold,
                                          color: Color.fromRGBO(251, 199, 0, 1.0)),
                                    ),
                                  ),
                                ),
                                ],
                            );
                          });
                    }
                    return CircularProgressIndicator();
                  }),
            ],
          ),
        ));
  }

FireStore Structure Image

我进行了更新并添加了新的帖子部分,但我在谷歌搜索后发现没有任何东西可以解决我的问题,而且我从 Firebase Firestore 官方文档中编辑了代码,但没有任何效果..因此查看或读取数据很困难对我来说。

提前感谢您的友好合作!

【问题讨论】:

  • 你在尝试 StreamBuilder 吗?
  • 是的,我试过 Streambuilder,但如果你有代码,我会测试你的代码。看看它是否有效
  • 能否分享您的数据模型以更好地了解您的数据结构?
  • 您的意思是 Firestore 数据?还是颤动整个代码?

标签: firebase flutter google-cloud-firestore


【解决方案1】:
final Future<QuerySnapshot<Map<String, dynamic>>> query = FirebaseFirestore
    .instance
    .collection('signals')
    .get();
// NB: This wont return documents where type doesn't exist.
var usersList;
final formatter = intl.NumberFormat("#,##0.0######"); // for price change
final percentageFormat = intl.NumberFormat("##0.0#"); // for price change
final GlobalKey<ExpansionTileCardState> cardA = new GlobalKey();

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Color.fromRGBO(34, 44, 59, 1.0),
    body: Center(
      child: Column(
        children: [
          SizedBox(
            height: 50.0,
          ),
          Image.asset(
            logoImage,
            fit: BoxFit.contain,
            color: Color.fromRGBO(251, 199, 0, 1.0),
            height: 100.0,
            width: 100.0,
          ),
          Text(
            '[users]',
            style: TextStyle(
              fontSize: 20,
              color: Color.fromRGBO(251, 199, 0, 1.0),
            ),
          ),
          FutureBuilder(
            future: query,
            builder: (context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
              if (snapshot.hasError) return Text('Something went wrong');
              if (snapshot.connectionState == ConnectionState.waiting)
                return CircularProgressIndicator();

              List<Map<String, dynamic>> lists =
                  snapshot.data.docs.map((e) => e.data() as Map<String, dynamic>).toList();
              return new ListView.builder(
                shrinkWrap: true,
                itemCount: lists.length,
                itemBuilder: (BuildContext context, int index) {
                  Divider(
                    thickness: 1.0,
                    height: 1.0,
                  );
                  return ExpansionTileCard(
                    baseColor: Color.fromRGBO(34, 44, 59, 1.0),
                    expandedColor: Color.fromRGBO(24, 31, 42, 1.0),
                    leading: CircleAvatar(
                      child: Image.asset(
                        "assets/images/giphyy.gif",
                      ),
                      backgroundColor: Colors.transparent,
                    ),
                    title: Text(
                      lists[index]["username"].toString(),
                      style: TextStyle(
                        color: Color.fromRGBO(251, 199, 0, 1.0),
                      ),
                    ),
                    children: <Widget>[
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16.0,
                            vertical: 8.0,
                          ),
                          child: Text(
                            lists[index]["userinfo"].toString(),
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Color.fromRGBO(251, 199, 0, 1.0),
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ],
      ),
    ),
  );
}

【讨论】:

  • 它给出了错误出错了。这是我的 Firestore 结构:i.imgur.com/uKzVBoo.png
  • if (snapshot.hasError) 行之前添加print(snapshot.error)。然后让我知道错误信息。此外,在您的 Firestore 结构中,向我展示 users 集合,因为这是我们获取的而不是 signals
  • 如果我更改为 if (!snapshot.hasError) return Text('Something went wrong');我会得到: NoSuchMethodError:getter 'dos' 在 null 上被调用。接收者:空
  • 对不起,我更改了结构并编辑了线程中的一些字符串(仅限名称/文档)用户 = 信号用户名 = 硬币名我将检查打印并恢复
  • 完美。别客气。请将答案标记为已接受。也谢谢你。
【解决方案2】:

更改并尝试此代码:

StreamBuilder(
  stream: dbRef.orderByChild("type").equalTo("Free").onValue,
  builder: (context,  snapshot) {
   if (!snapshot.hasData || snapshot.hasError) {
     return Text('ERROR!');
   }
   if (snapshot.connectionState == ConnectionState.waiting) {
     return Text('Loading..');
   }
   if (snapshot.hasData) {
      lists.clear();
      Map<dynamic, dynamic> values = snapshot.data.value;
      values.forEach((key, values) {
      lists.add(values);
     });
   }
  return new ListView.builder... // than write you code

【讨论】:

  • 仍然显示 Firebase 实时数据库,如:final dbRef = FirebaseDatabase.instance.reference().child("users");我需要更改为 FirebaseFirestore。
  • 是的,当然,你写的代码旧firebase插件名称))我也搞错了)
  • 那么有什么解决办法吗?
  • 你能告诉我 Firebase Firestore 数据模型吗?在我可以为你编写正确的代码之后。
  • 给你,伙计:i.imgur.com/uKzVBoo.png
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 2021-11-08
  • 2021-01-21
  • 2020-04-19
  • 2021-09-30
  • 2020-02-24
相关资源
最近更新 更多