firebase 如何在flutter中从云firestore获取数据?

hgqdbh6s  于 2023-01-18  发布在  Flutter
关注(0)|答案(3)|浏览(271)

我想从flutter的firestore中获取联系方式,如电话号码、电子邮件地址、网站网址以及社交媒体网址,我做了编码直接在应用程序中显示联系方式,但我需要从firestore中获取数据,因为如果我将来需要更改联系方式,这对我很有好处。
"我的密码"

import 'package:cloud_firestore/cloud_firestore.dart';

class AboutPage extends StatelessWidget {
  const AboutPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: LightColor.white,
      appBar: CustomAppBar(
        isBackButton: true,
        title: customTitleText(
          'Contact us',
        ),
      ),
      body: ListView(
        physics: BouncingScrollPhysics(),
        children: <Widget>[
          HeaderWidget(
            'Feel free to contact us',
            secondHeader: true,
          ),
          SettingRowWidget(
            "Phone",
            vPadding: 0,
            showDivider: false,
            onPressed: () {
              Utility.launchURL(///i want to display this url from firestore///
                  "tel:+918889999888");
            },
          ),
          
          HeaderWidget('Social media'),
          SettingRowWidget("Facebook", showDivider: true, onPressed: () {
            Utility.launchURL( ///i want to display this url from firestore/// 
"https://facebook.com/ecways");
          }),

      HeaderWidget('Website'),
          SettingRowWidget("Open website", showDivider: true, onPressed: () {
            Utility.launchURL( ///i want to display this url from firestore/// 
"https://facebook.com/");
          }),    
          
        ],
      ),
    );
  }
}

我创建了firestore数据库与收集名称“我的联系人”和文档名称“详细信息”,我也创建了电话,电子邮件,网站和其他字段。现在我只想知道如何显示我的应用程序与我的编码收集。

c86crjj0

c86crjj01#

首先,您必须将firestore数据库更改为

应该有一个名为联系人的数组,里面应该有3个Map根据您的数据。
然后在screen类中创建一个列表。

List contacts;

然后创建一个函数从firestore检索数据。

Future<List> fetchAllContact() async {
    List contactList = [];
    DocumentSnapshot documentSnapshot =
        await firestore.collection('my_contact').doc('details').get();
    contactList = documentSnapshot.data()['contacts'];
    return contactList;
  }

然后在initState函数中调用此函数。

@override
  void initState() {
    super.initState();
    fetchAllContact().then((List list) {
      setState(() {
        contacts = list;
      });
    });
  }

最后将listView替换为listViewBuilder。

Container(
                    child: ListView.builder(
                        padding: EdgeInsets.all(10),
                        itemCount: contacts.length,
                        itemBuilder: (context, index) {
                          return CustomTile(
                            mini: false,
                            onTap: () {},
                            title: Text(
                              contacts[index]['headerTitle'] != null
                                  ? contacts[index]['headerTitle']
                                  : '',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: "Arial",
                                  fontSize: 19),
                            ),
                            subtitle: Text(
                              contacts[index]['value'] != null
                                  ? contacts[index]['value']
                                  : '',
                              style: TextStyle(
                                color: UniversalVariables.greyColor,
                                fontSize: 14,
                              ),
                            ),
                            leading: Container(
                              constraints:
                                  BoxConstraints(maxHeight: 60, maxWidth: 60),
                              child: Stack(
                                children: <Widget>[
                                  CircleAvatar(
                                    maxRadius: 30,
                                    backgroundColor: Colors.grey,
                                    backgroundImage: NetworkImage(
                                        "https://avatars.githubusercontent.com/u/49371842?v=4"),
                                  ),
                                  Align(
                                    alignment: Alignment.bottomRight,
                                    child: Container(
                                      height: 13,
                                      width: 13,
                                      decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          color:
                                              UniversalVariables.onlineDotColor,
                                          border: Border.all(
                                              color:
                                                  UniversalVariables.blackColor,
                                              width: 2)),
                                    ),
                                  )
                                ],
                              ),
                            ),
                          );
                        }
                        ),
                  )

我就是这么做的。谢谢...

vfh0ocws

vfh0ocws2#

flutterfire现在有一个很好的演练。请参考本节从firestore www.example.com获取数据https://firebase.flutter.dev/docs/firestore/usage/#collections--documents

p1iqtdky

p1iqtdky3#

使用null Safety更新2023

有两种方式:

1.流生成器

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

2.未来构建者

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

流生成器

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

另请参阅:How to use StreamBuilder and FutureBuilder for single and multiple documents

相关问题