我想知道如何使用StreamBuilder从FireStore到Ffltter应用程序获取数据.我创建了必要的样板代码,并在下面的代码中构建并运行了小部件 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]),
                  )
                ],
              )
            ],
          ),
        ),
      ],
    );
  }

}

实际应用 enter image description here个 请说明一下这一点.TKS.

推荐答案

这应该适用于一件物品

  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"];

);

Flutter相关问答推荐

Flutter iOS日期 Select 器UI中限制日期范围?

Android Emulator冻结,但在调整窗口大小时解冻

我可以在iOS设备上使用Ffltter实现Google Pay按钮吗?

Flutter -如何停止块监听程序在后台堆栈中运行

更改BottomNavigationBar onTap?的大小

应为Map String,dynamic类型的值,但得到的值为type()= Map String,dynamic'

在VSCode中运行应用程序而不进行调试时,控制台仍显示为调试模式

带有附加图像的ListTile

Flutter Xcode 15 错误(Xcode):DT_TOOLCHAIN_DIR 无法用于判断 LIBRARY_SEARCH_PATHS

当 Dart SDK 版本范围不匹配时,为什么依赖解析器不会抛出错误?

如何在 Flutter 中创建厚度沿着容器逐渐减小的边框

如何使用 Material3 创建带有高度的完美白色提升按钮?

如何动态获取任何小部件的像素?

如何根据应用程序主题(深色和浅色)更改谷歌 map 的主题?

Flutter 中出现错误空判断运算符用于空值

为什么 orientation == Orientation.portrait 总是正确的,尽管我的设备已经处于横向

在 Flutter 中,如何使用文本字段和方形图像进行行布局

我收到这个错误我无法解决

如何使用 Riverpod 在运行时动态创建提供程序?

如何在Flutter 中将列表的模型类型转换为数组?