firebase 从消防站到消防站

ctehm74n  于 2023-01-18  发布在  其他
关注(0)|答案(7)|浏览(131)

我想知道如何使用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]),
                  )
                ],
              )
            ],
          ),
        ),
      ],
    );
  }

}

实际应用程序

请阐明这一点。谢谢。

92dk7w1h

92dk7w1h1#

这应该适用于一个项目

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

);
t5zmwmid

t5zmwmid2#

在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");
        }
    },
)
jc3wubiy

jc3wubiy3#

根据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);
    });
  },
);
41zrol4v

41zrol4v4#

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,
        ),
          ],
        )
      ],
    ),
  ),
);  }

对于其他面临同样问题的人来说,卡片和流构建器将提供一个解决方案。小部件在声明之前包含卡片,并在主体中包含下一部分:

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();
              }
            },
          )
        ],
      ),
0ve6wy6x

0ve6wy6x5#

针对2022年Flutter 2.10cloud_firestore的更新:^3.1.11.您可以使用StreamBuilder从集合中检索数据

Stream collectionStream = FirebaseFirestore.instance.collection('users').snapshots();

      StreamBuilder<QuerySnapshot>(
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final messages = snapshot.data!.docs;
                List<Text> messageWidgets = [];

                for (var element in messages) {
                  final messageText = element['text'];
                  final messageSender = element['sender'];

                  final messageWidget =
                      Text('$messageText from $messageSender');
                  messageWidgets.add(messageWidget);
                }
                return Column(
                  children: messageWidgets,
                );
              }
              return const Text('Error');
            },
            stream:collectionStream),
shyt4zoc

shyt4zoc6#

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(),
                );
              }),
c90pui9n

c90pui9n7#

使用null safety更新2023

多年来,许多事情发生了变化,我想更新与最新的可能的工作答案。

适用于多个文档的StreamBuilder

final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('users').snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<QuerySnapshot>(
          stream: _usersStream,
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }
            return ListView(
                children: snapshot.data!.docs.map((DocumentSnapshot document) {
              Map<String, dynamic> data =
                  document.data()! as Map<String, dynamic>;
              return ListTile(
                title: Text(data['fullName']), // 👈 Your valid data here
              );
            }).toList());
          },
        ),
      ),
    );
  }

用于单个文档的StreamBuilder

class _UserInformationState extends State<UserInformation> {
  final _usersStream = FirebaseFirestore.instance
      .collection('users')
      .doc(FirebaseAuth.instance.currentUser!.uid) // 👈 Your document id change accordingly
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream: _usersStream,
          builder:
              (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
            if (snapshot.hasError) {
              return const Text('Something went wrong');
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Text("Loading");
            }
            Map<String, dynamic> data =
                snapshot.data!.data()! as Map<String, dynamic>;
            return Text(data['fullName']);
          },
        ),
      ),
    );
  }
}

相关问题