firebase 如何从Firestore Flutter中读取数据

vfhzx4xs  于 2023-01-18  发布在  Flutter
关注(0)|答案(8)|浏览(128)

我想从列表中的firestore读取数据我不想使用streambuilder我想单独访问文档字段我尝试了这个但没有工作

class ProductList extends StatelessWidget {

  Stream<DocumentSnapshot> snapshot =  Firestore.instance.collection("listofprods").document('ac1').snapshots();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black)
                ),
                child: ListTile(
                      title: Text(snapshot['name']),//here error
                ),
              )
            ],
4c8rllxm

4c8rllxm1#

As Per 2021 :
 streamSnapshot.data.docs

文件变更

@override
      Widget build(BuildContext context) {
        return Scaffold(
            body: StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection('chats/XYSDa16jZBO5CUMwIk0h/messages')
              .snapshots(),
          builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
            return ListView.builder(
              itemCount: streamSnapshot.data.docs.length,
              itemBuilder: (ctx, index) =>
                  Text(streamSnapshot.data.docs[index]['text']),
            );
          },
        ));

  }
svujldwt

svujldwt2#

试试这个:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class WeightChart extends StatefulWidget {
  @override
  _WeightChartState createState() => _WeightChartState();
}

class _WeightChartState extends State<WeightChart>  {
  dynamic data;

  Future<dynamic> getData() async {

    final DocumentReference document =   Firestore.instance.collection("listofprods").document('ac1');

    await document.get().then<dynamic>(( DocumentSnapshot snapshot) async{
     setState(() {
       data =snapshot.data;
     });
    });
 }

 @override
  void initState() {

    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: const Text('Weight'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black)
              ),
              child: ListTile(
                    title: Text(data['name']),//here error
              ),
            )
          ]
        )
      ),
    );
  }
}
ndh0cuux

ndh0cuux3#

在一个无状态的小部件中,我使用了以下代码:

  • 在生成中第一次运行的函数
  • 此函数需要为"async-await"才能获取数据
  • 使用toString、get和data访问所需元素。

代码:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

DocumentSnapshot snapshot; //Define snapshot

class ProductList extends StatelessWidget {
  void getData()async{ //use a Async-await function to get the data
    final data =  await Firestore.instance.collection("listofprods").document('ac1').get(); //get the data
     snapshot = data;
  }
  @override
  Widget build(BuildContext context) {
    getData(); //run the function in build
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black)
                ),
                child: ListTile(
                      title: Text(snapshot.data['name'].toString()),//ok no errors.
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

最后一个代码可能会在cloud_firestore的不同版本上得到一些错误,我使用的版本是

  • 云_消防商店:^0.13.7
  • Firebase _核心:^0.4.5

其他错误是文本上有一些空值的红色屏幕,通过FutureBuilder直接调用数据来修复,如下所示:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ProductList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Future<String> data2() async {
      var data1 = (await Firestore.instance
              .collection('listofprods')
              .document('ac1')
              .get())
          .data['name']
          .toString();
      return data1;
    }
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                decoration:
                    BoxDecoration(border: Border.all(color: Colors.black)),
                child: ListTile(
                  title: FutureBuilder(
                    future: data2(),
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      print(snapshot.data);
                      return Text(snapshot.data);
                    },
                  ), //ok no errors.
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
x7rlezfr

x7rlezfr4#

可以使用StreamBuilder

StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('books').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.hasError)
      return new Text('Error: ${snapshot.error}');
    switch (snapshot.connectionState) {
      case ConnectionState.waiting: return new Text('Loading...');
      default:
        return new ListView(
          children: snapshot.data.documents.map((DocumentSnapshot document) {
            return new ListTile(
              title: new Text(document['title']),
              subtitle: new Text(document['author']),
            );
          }).toList(),
        );
qc6wkl3g

qc6wkl3g5#

这在FlutterFire中有效!我使用了DocumentSnapshot并等待。
通过使用DocumentSnapshot,您可以获得包括文档字段及其值的文档。
DocumentSnapshot包含从Cloud Firestore数据库中的文档读取的数据。可以使用data()或get()提取数据以获取特定字段。
关键字await将一直等到所有异步函数完成。
可以使用await关键字来获取异步表达式的完整结果。await关键字仅在异步函数中有效。

import 'package:cloud_firestore/cloud_firestore.dart';

final db = FirebaseFirestore.instance;

// Get document with ID totalVisitors in collection dashboard
await db.collection('dashboard').doc('totalVisitors').get()
  .then((DocumentSnapshot documentSnapshot) {
                            
    // Get value of field date from document dashboard/totalVisitors
    firestoreDate = documentSnapshot.data()['date'];

    // Get value of field weekOfYear from document dashboard/totalVisitors
    firestoreWeek = documentSnapshot.data()['weekOfYear'];

  }
);
0lvr5msh

0lvr5msh6#

Streambuilder用于flutter中的流

StreamBuilder<DocumentSnapshot>(
     stream: Firestore.instance.collection("listofprods").document('ac1').snapshots(),
     builder: (context, snapshot) {
       if (!snapshot.hasData) return LinearProgressIndicator();

       return _buildList(context, snapshot.data.documents);
     },
   );
fcy6dtqo

fcy6dtqo7#

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class DataFetch extends StatefulWidget {
  const DataFetch({Key key}) : super(key: key);
  @override
  _DataFetchState createState() => _DataFetchState();
}
class _DataFetchState extends State<DataFetch> {
  List<Model> list=[];
  void fetchData()async{
    var data=await FirebaseFirestore.instance.collection("Items").get();
    for(int i=0;i<data.docs.length;i++){
      Model model=Model(data.docs[i].data()['title'], data.docs[i].data()['price'],data.docs[i].data()['imageURL'],data.docs[i].data()['desc'], data.docs[i].data()['seller']);
      list.add(model);
    }
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          child: list.length==0? Center(child: Text("No Post")):ListView.builder(itemCount: list.length,
            itemBuilder:(_,index){
              return MyUI(list[index].title, list[index].url, list[index].price, list[index].desc, list[index].seller);
            },
          ),
        ),
      ),
    );
  }
  Widget MyUI(String title,String url,String price,String desc,String seller){
    return Container(
      child: Column(
        children: [
          Text(title),
          Image.network(url),
          Text(price),
          Text(desc),
          Text(seller)
        ],
      ),
    );
  }
}

class Model{
  String title,price,url,desc,seller;
  Model(this.title,this.price,this.url,this.desc,this.seller);
}
thigvfpy

thigvfpy8#

使用null Safety更新2023

有两种方式:

1.流生成器

当您希望不断听取更改,并希望数据在不进行热重新加载/重新启动的情况下得到更新时

2.未来构建者

当您只想获取文档一次,并且不需要不断地监听文档的更改时。

流生成器

1.多个文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<QuerySnapshot>(
          stream: FirebaseFirestore
                  .instance.
                  .collection('users') // 👈 Your desired collection name here
                  .snapshots(), 
          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());
          },
        ),
      ),
    );
  }

2.单个文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          stream:  FirebaseFirestore
                   .instance
                   .collection('users')
                   .doc(FirebaseAuth.instance.currentUser!.uid) // 👈 Your document id change accordingly
                   .snapshots(), 
          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']); // 👈 your valid data here
          },
        ),
      ),
    );
  }

未来建筑师

1.多个文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: FutureBuilder<QuerySnapshot>(
        future: FirebaseFirestore
                .instance
                .collection('users') // 👈 Your collection name here
                .get(), 
        builder: (_, snapshot) {
          if (snapshot.hasError) return Text('Error = ${snapshot.error}');
          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['avatar']), // 👈 Your valid data here
            );
          }).toList());
        },
      )),
    );
  }

2.单个文档

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
        future: FirebaseFirestore.instance
            .collection('users')
            .doc(FirebaseAuth.instance.currentUser!.uid)  // 👈 Your document id change accordingly
            .get(),
        builder: (_, snapshot) {
          if (snapshot.hasError) return Text('Error = ${snapshot.error}');
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("Loading");
          }
          Map<String, dynamic> data = snapshot.data!.data()!;
          return Text(data['fullName']); //👈 Your valid data here
        },
      )),
    );
  }

相关问题