【问题标题】:How to get a single data from Firebase without using FutureBuilder or StreamBuilder in Flutter如何在不使用 Flutter 中的 FutureBuilder 或 StreamBuilder 的情况下从 Firebase 获取单个数据
【发布时间】:2021-01-21 12:18:06
【问题描述】:
我想从 Firestore 中检索单个数据或字段。在这种情况下,像 user1 的 firstName、lastName 或 title
我浏览了 FlutterFire 文档,它使用 FutureBuilder 从 Firestore 读取数据。我也在 Stack Overflow 上搜索过这个问题,但没有得到任何完美的答案。
【问题讨论】:
标签:
firebase
flutter
dart
google-cloud-firestore
【解决方案1】:
回答我自己的问题,因为我没有找到任何完美的答案。
//Initialising as 'loading..' because text widget (where you'll be using these variables) can't be null
String firstName = 'loading...'
String lastName = 'loading...'
String title = 'loading...'
class Screen extends StatefulWidget {
@override
_ScreenState createState() => _ScreenState();
}
class _ScreenState extends State<Screen> {
//Creating a reference to the collection 'users'
CollectionReference collectionReference =
FirebaseFirestore.instance.collection('users');
//This function will set the values to firstName, lastName and title from the data fetched from firestore
void getUsersData() {
collectionReferenceToOrderacWeb.doc('user1').get().then((value) {
//'value' is the instance of 'DocumentSnapshot'
//'value.data()' contains all the data inside a document in the form of 'dictionary'
var fields = value.data();
//Using 'setState' to update the user's data inside the app
//firstName, lastName and title are 'initialised variables'
setState(() {
firstName = fields['firstName'];
lastName = fields['lastName'];
title = fields['title'];
});
});
}
@override
Widget build(BuildContext context) {
return Container();
}
}
【解决方案2】:
只是为那些没有找到他们正在寻找的确切内容的人重新构建上述解决方案(获取集合中所有文档的数据)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class Screen extends StatefulWidget{
final String documentId;
Screen({this.documentId});
@override
_ScreenState createState() => _ScreenState();
}
class _ScreenState extends State<Screen>{
String itemName = '';
String itemImage = ''; //Initializing string bcz image requires a path
String itemQuantity = '';
CollectionReference collectionReference =
FirebaseFirestore.instance.collection('CollectionName');
@override
void initState(){
//documentId is passed from previous widget
collectionReference.doc(widget.documentId).get().then((value) {
//'value' is the instance of 'DocumentSnapshot'
//'value.data()' contains all the data inside a document in the form of 'dictionary'
setState(() {
//name, image, quantity are the fields of document
itemName = value.data()['name'];
itemImage = value.data()['image'];
itemQuantity = value.data()['quantity'].toString(); //quantity field is of type number in firebase
//while retrieving numerical value from firebase, convert it to string before displaying
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Image.network(itemImage),
Text(itemName),
Text(itemQuantity),
]
));
}
}