【问题标题】:Stream builder from firestore to flutter从 Firestore 到 Flutter 的 Stream Builder
【发布时间】:2018-11-05 15:42:20
【问题描述】:

我想知道如何使用 streambuilder 将数据从 firestore 获取到 Flutter 应用程序。我创建了必要的样板代码我已经构建并运行了小部件,并且在下面的代码中 headimageassetpath 只是存在于 firestore 中的 URL 字符串。

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
      new StreamBuilder(
        stream: Firestore.instance.collection('Items').snapshots(),
        builder: (_, AsyncSnapshot<QuerySnapshot> snapshot) {
          var items = snapshot.data?.documents ?? [];
          return new Lost_Card(
            headImageAssetPath : snapshot.data.documents.map()(['url'],)   

          );
        },
      )

我的火库:

完整代码:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class LostPage extends StatefulWidget {
  @override
  _LostPage createState() => new _LostPage();
}

class _LostPage extends State<LostPage> {

  //temp vars
  final String firebasetest = "Test";

  //firestore vars
  final DocumentReference documentReference =
      Firestore.instance.document("Items/Rusty");


  //CRUD operations
  void _add() {
    Map<String, String> data = <String, String>{
      "name": firebasetest,
      "desc": "Flutter Developer"
    };
    documentReference.setData(data).whenComplete(() {
      print("Document Added");
    }).catchError((e) => print(e));
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
      new StreamBuilder(
        stream: Firestore.instance.collection('Items').snapshots(),
        builder: (_, AsyncSnapshot<QuerySnapshot> snapshot) {
          var items = snapshot.data?.documents ?? [];


          return new Lost_Card(
            headImageAssetPath : snapshot.data.documents.map()(['url'],)


          );
        },
      )

      /*new Lost_Card(
        headImageAssetPath: "https://i.imgur.com/FtaGNck.jpg" ,
        title: "Mega Dish",
        noro: "old",


      )*/,
      floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.add),
          onPressed: _add),
    );
  }
}

class Lost_Card extends StatelessWidget
{

  //All the card variables
  final String headImageAssetPath;
  final IconData icon;
  final Color iconBackgroundColor;
  final String title;
  final String noro;
  final int price;
  final ShapeBorder shape;

  Lost_Card({

    this.headImageAssetPath,  //used
    this.icon,
    this.iconBackgroundColor,
    this.title, //used
    this.noro,  //used
    this.price,

  });



  @override
  Widget build(BuildContext context) {





    // TODO: implement build
   return GridView.count(
      shrinkWrap: true,
      crossAxisCount: 2,
      children: <Widget>[
        Card(
          child: Column(
            // mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                child: Stack(
                  fit: StackFit.expand,
                  children: <Widget>[
                    Container(
                      height: MediaQuery.of(context).size.height / 4,
                      width: MediaQuery.of(context).size.height / 2.5,

                      child: DecoratedBox(
                        decoration: BoxDecoration(
                          image: DecorationImage(
                              image: NetworkImage(
                                  headImageAssetPath),
                              fit: BoxFit.cover),
                        ),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Align(
                        alignment: FractionalOffset.topLeft,
                        child: CircleAvatar(
                          backgroundColor: Colors.redAccent,
                          radius: 15.0,
                          child: Text(
                            noro,
                            textScaleFactor: 0.5,
                          ),
                        ),
                      ),
                    ),
                    Align(
                      alignment: FractionalOffset.topRight,
                      child: Container(
                        color: Colors.blueAccent,
                        height: 35.0,
                        width: 35.0,
                        child: Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Icon(Icons.account_circle),
                              Text(
                                "1P",
                                textScaleFactor: 0.5,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Center(
                child: Container(
                  padding: const EdgeInsets.all(8.0),
                  alignment: FractionalOffset.bottomCenter,
                  child: Text(
                    title,
                    style: TextStyle(
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  FlatButton(
                    child: Text(
                      "Add To Cart",
                      style: TextStyle(color: Colors.grey[500]),
                    ),
                    onPressed: () => null,
                  ),
                  Text(
                    "\$5",
                    style: TextStyle(color: Colors.grey[500]),
                  )
                ],
              )
            ],
          ),
        ),
      ],
    );
  }

}

实际应用 请对此有所了解。谢了。

【问题讨论】:

标签: firebase google-cloud-firestore flutter


【解决方案1】:

这应该适用于一个项目

  body: new StreamBuilder(
    stream: Firestore.instance.collection("collection").snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return Text(
          'No Data...',
        );
      } else { 
          <DocumentSnapshot> items = snapshot.data.documents;

          return new Lost_Card(
          headImageAssetPath : items[0]["url"]
          );
      }

如果您想从许多文档中创建列表构建器,请像这样使用它

        return new ListView.builder(
            itemCount: snapshot.data.documents.length,
            itemBuilder: (context, index) {
              DocumentSnapshot ds = snapshot.data.documents[index];
              return new Lost_Card(
                headImageAssetPath : ds["url"];

);

【讨论】:

  • 你拯救了这一天!
  • 在找到答案之前浪费了一天的时间进行测试。非常感谢.. 现在卡在其他错误上。 XD 现在将修复它们.. :)
  • 我想在一个函数中准备dataList List 类型变量,该函数将在InitState 函数中调用,然后我想将该dataList List 类型变量传递给build 函数以显示记录dataList 列表类型变量。请分享您的建议。我能怎么做?谢谢。
  • 对我来说,snapshot.data 的类型是 Object?,所以这不起作用
【解决方案2】:

在 Flutter 2 中使用 StreamBuilder 访问文档

StreamBuilder<QuerySnapshot>(
    stream: FirebaseFirestore.instance.collection('products').snapshots(),
    builder: (context, snapshot) {
        if (snapshot.hasData) {
        return ListView.builder(
            itemCount: snapshot.data!.docs.length,
            itemBuilder: (context, index) {
                DocumentSnapshot doc = snapshot.data!.docs[index];
                return Text(doc['name']);
            });
        } else {
        return Text("No data");
        }
    },
)

【讨论】:

    【解决方案3】:
    Card buildItem(DocumentSnapshot doc) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              'name: ${doc.data['name']}',
              style: TextStyle(fontSize: 24),
            ),
            Text(
              'todo: ${doc.data['todo']}',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              'Age: ${doc.data['age']}',
              style: TextStyle(fontSize: 10),
            ),
            SizedBox(
              height: 12,
            ),
              ],
            )
          ],
        ),
      ),
    );  }
    

    对于将面临同样问题的其他人,卡片和流生成器将代表一个解决方案。 Widget 在它声明之前有 Card 并且在 body 中有下一部分:

     body: ListView(
            padding: EdgeInsets.all(8),
            children: <Widget>[
              Form(
                key: _formKey,
                child: buildTextFormField(),
              ),
              StreamBuilder<QuerySnapshot>(
                stream: db
                    .collection('CRUD')
                    .snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Column(
                        children: snapshot.data.documents
                            .map((doc) => buildItem(doc))
                            .toList());
                  } else {
                    return SizedBox();
                  }
                },
              )
            ],
          ),
    

    【讨论】:

      【解决方案4】:

      根据 Firebase FireStore 2021 年的新变化,您可以使用 StreamBuilder 从集合中检索数据,如下所示

      final _mFirestore = FirebaseFirestore.instance;
      
      return StreamBuilder<QuerySnapshot>(
        stream:
            _mFirestore.collection(kFirebaseCollectionName).snapshots(),
        builder: (context, snapshots) {
          if (!snapshots.hasData) {
            return Center(
              child: Text('Data not available',),
            );
          }
          final messages = snapshots.data.docs;
          List<Text> textWidgets = [];
      
          messages.forEach((element) {
            final messageText = element['text'];
            final messageSender = element['sender'];
      
            final textWidget = Text('$messageText, $messageSender');
            textWidgets.add(messageBubbleWidget);
          });
        },
      );
      

      【讨论】:

        【解决方案5】:
        StreamBuilder<List<UData>>(
                      stream: AdminData().getDrivers,
                      builder: (context, snapshot) {
                        return ListView(
                          children: snapshot.data.map((document) {
                            return hadCard(
                              widget: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceAround,
                                children: [
                                  hadText(title: document.name),
                                  hadText(title: document.phone),
                                  hadText(title: document.Driver),
                                ],
                              ),
                            );
                          }).toList(),
                        );
                      }),
        

        【讨论】:

        • 我想在函数中准备dataList List 类型变量,该函数将在InitState 函数中调用,然后我想将该dataList List 类型变量传递给build 函数以显示记录dataList 列表类型变量。请分享您的建议。我能怎么做?谢谢。
        猜你喜欢
        • 2020-09-07
        • 2021-09-17
        • 2021-06-04
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 2020-07-30
        • 2021-04-04
        相关资源
        最近更新 更多