如何在Flutter中从Firebase获取数据

cld4siwp  于 2023-01-18  发布在  Flutter
关注(0)|答案(5)|浏览(130)

我正在构建一个flutter应用程序并使用cloud-firestore,这是我的数据库x1c 0d1x的外观
我想要一个函数,检索集合中的所有文档,称为“驱动程序列表”的字符串数组,我已经使用过,但它让他们回到一个新屏幕的列表视图

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

nwsw7zdq1#

这有一些额外的逻辑来删除潜在的重复记录,但是您可以使用类似下面的方法从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

l2osamch

l2osamch2#

*获取一次性数据:

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

6ojccjat3#

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

byqmnocz4#

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

ruoxqz4g5#

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

相关问题