![](/img/trans.png)
[英]How to fetch the data from cloud_firestore and display it in the TextField in flutter
[英]How to fetch data from cloud firestore in flutter?
我想從 flutter 中的 firestore 獲取聯系方式,例如電話號碼、email 地址、網站 url 以及社交媒體網址。我完成了編碼以直接在應用程序中顯示聯系方式,但我需要從 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/");
}),
],
),
);
}
}
我使用集合名稱“my_contact”和文檔名稱“details”創建了 firestore 數據庫,還為電話、email、網站等創建了字段。 現在我只想知道如何使用我的代碼在我的應用程序中顯示該集合。
flutterfire 現在可以很好地完成它。 請參閱此部分以從 firestore https://firebase.flutter.dev/docs/firestore/usage/#collections--documents獲取數據
應該有一個名為 contacts 的數組,里面應該有 3 個根據您的數據的地圖。
然后在您的屏幕 class 中創建一個列表。
List contacts;
然后創建 function 以從 firestore 檢索數據。
Future<List> fetchAllContact() async {
List contactList = [];
DocumentSnapshot documentSnapshot =
await firestore.collection('my_contact').doc('details').get();
contactList = documentSnapshot.data()['contacts'];
return contactList;
}
然后在 initState function 中調用這個 function。
@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)),
),
)
],
),
),
);
}
),
)
我就是這樣做的。 謝謝...
當你想不斷地監聽變化,並希望數據在沒有熱重載/重啟的情況下得到更新
當你只想獲取文檔一次,而不需要一直監聽文檔的變化時。
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.