繁体   English   中英

如何从flutter中获取firebase的数据

[英]how to get data from firebase in flutter

我正在构建一个 flutter 应用程序并使用 cloud-firestore,这就是我的数据库的样子在此处输入图像描述

我想要一个 function 来检索名为“Driver List”的集合中的所有文档,这些文档位于我已经使用过的字符串数组中,但它会将它们返回到新屏幕的列表视图中

class DriverList extends StatelessWidget {@overrideWidget build(BuildContext context) {
    return new StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('DriverList').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return new Text('Loading...');
        return new ListView(
          children: snapshot.data.documents.map((DocumentSnapshot document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text(document['phone']),
            );
         }).toList(),
       );
     },
   );
 }
}

这有一些额外的逻辑来删除可能重复的记录,但您可以使用类似以下的内容从 Firestore 检索数据。

我们可以访问集合引用,然后列出查询结果,然后为 Firestore 返回的数据创建本地模型对象,然后返回这些模型对象的列表。

  static Future<List<AustinFeedsMeEvent>> _getEventsFromFirestore() async {
CollectionReference ref = Firestore.instance.collection('events');
QuerySnapshot eventsQuery = await ref
    .where("time", isGreaterThan: new DateTime.now().millisecondsSinceEpoch)
    .where("food", isEqualTo: true)
    .getDocuments();

HashMap<String, AustinFeedsMeEvent> eventsHashMap = new HashMap<String, AustinFeedsMeEvent>();

eventsQuery.documents.forEach((document) {
  eventsHashMap.putIfAbsent(document['id'], () => new AustinFeedsMeEvent(
      name: document['name'],
      time: document['time'],
      description: document['description'],
      url: document['event_url'],
      photoUrl: _getEventPhotoUrl(document['group']),
      latLng: _getLatLng(document)));
});

return eventsHashMap.values.toList();
}

来源: https ://github.com/dazza5000/austin-feeds-me-flutter/blob/master/lib/data/events_repository.dart#L33

  • 获取一次性数据:

     var collection = FirebaseFirestore.instance.collection('DriverList'); var querySnapshot = await collection.get(); for (var queryDocumentSnapshot in querySnapshot.docs) { Map<String, dynamic> data = queryDocumentSnapshot.data(); var name = data['name']; var phone = data['phone']; }
  • 每次更改时获取数据,使用StreamBuilder

     StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( stream: FirebaseFirestore.instance.collection('DriverList').snapshots(), builder: (_, snapshot) { if (snapshot.hasError) return Text('Error = ${snapshot.error}'); if (snapshot.hasData) { final docs = snapshot.data!.docs; return ListView.builder( itemCount: docs.length, itemBuilder: (_, i) { final data = docs[i].data(); return ListTile( title: Text(data['name']), subtitle: Text(data['phone']), ); }, ); } return Center(child: CircularProgressIndicator()); }, )
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';

    class LoadDataFromFirestore extends StatefulWidget {
      @override
      _LoadDataFromFirestoreState createState() => _LoadDataFromFirestoreState();
    }

    class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
      @override
      void initState() {
        super.initState();
        getDriversList().then((results) {
          setState(() {
            querySnapshot = results;
          });
        });
      }

      QuerySnapshot querySnapshot;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: _showDrivers(),
        );
      }

    //build widget as prefered
    //i'll be using a listview.builder
      Widget _showDrivers() {
        //check if querysnapshot is null
        if (querySnapshot != null) {
          return ListView.builder(
            primary: false,
            itemCount: querySnapshot.documents.length,
            padding: EdgeInsets.all(12),
            itemBuilder: (context, i) {
              return Column(
                children: <Widget>[
//load data into widgets
                  Text("${querySnapshot.documents[i].data['activation']}"),
                  Text("${querySnapshot.documents[i].data['car1']}"),
                  Text("${querySnapshot.documents[i].data['car2']}"),
                  Text("${querySnapshot.documents[i].data['car5']}"),
                  Text("${querySnapshot.documents[i].data['name']}"),
                  Text("${querySnapshot.documents[i].data['phone']}"),
                ],
              );
            },
          );
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      }

      //get firestore instance
      getDriversList() async {
        return await Firestore.instance.collection('DriversList').getDocuments();
      }
    }
body: SafeArea(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        StreamBuilder(
          stream:
              FirebaseFirestore.instance.collection('messages').snapshots(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Center(
                child: Text(snapshot.error.toString()),
              );
            }
            if (snapshot.hasData) {
              final messages = snapshot.data!.docs;
              List<Text> messageWigdets = [];
              for (var message in messages) {
                final messageText = message['text'];
                final messageSender = message['sender'];
                final messageWigdet =
                    Text('$messageText from $messageSender');
                messageWigdets.add(messageWigdet);
              }
              return Expanded(
                child: ListView(
                  children: [...messageWigdets],
                ),
              );
            }
            return const CircularProgressIndicator.adaptive();
          },
        ),

使用null Safety更新 2023


有2种方式:

1.StreamBuilder

当你想不断地监听变化,并希望数据在没有热重载/重启的情况下得到更新

2.未来建造者

当你只想获取文档一次,而不需要一直监听文档的变化时。


StreamBuilder

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

这可以通过两种方式完成:

  1. StreamBuilder :当你想不断地监听变化,并希望数据在没有热重载/重启的情况下得到更新
  2. FutureBuilder :当你只想获取文档一次,而不需要一直监听文档的变化时。

StreamBuilder

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

未来建造者

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM