【发布时间】:2021-01-18 03:14:35
【问题描述】:
我的 CustomerNotifier 类中有一个函数,它从 Firebase 中读取所有客户作为列表,如下所示:
getCustomers(CustomerNotifier customerNotifier) async {
String userId = (await FirebaseAuth.instance.currentUser()).uid;
print('Current logged in user uid is: $userId');
var snapshot = await customerCollection
.orderBy('created_at', descending: true)
.getDocuments();
List<Customer> _customerList = [];
snapshot.documents.forEach((document) {
Customer customer = Customer.fromMap(document.data);
_customerList.add(customer);
});
customerNotifier.customerList = _customerList;
}
我有另一个功能来更新或创建新客户并保存到 Firebase,如下所示:
Future updateCustomer(Customer customer, bool isUpdating) async {
CollectionReference customerRef =
await Firestore.instance.collection('customer');
if (isUpdating) {
customer.updatedAt = Timestamp.now();
await customerRef.document().updateData(customer.toMap());
print('updated customer with id: ${customer.id}');
} else {
customer.createdAt = Timestamp.now();
DocumentReference documentReference =
await customerRef.add(customer.toMap());
customer.id = documentReference.documentID;
print('created customer successfully with id: ${customer.id}');
await documentReference.setData(customer.toMap(), merge: true);
addCustomer(customer);
}
notifyListeners();
}
通过上述两种方法,我曾经成功地读取客户数据并将其写入我的 Firebase。但是,我试图只读取当前登录用户创建和更新的数据。所以来自其他stackoverflow线程的建议,我被建议将我的customer.id设置为userId,其中userId == currentUser().uid。我可以使用更新版本的 updateCustomer 成功写入我的数据库,如下所示:
Future updateCustomer(Customer customer, bool isUpdating) async {
CollectionReference customerRef =
await Firestore.instance.collection('customer');
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String userId = user.uid;
print('Current logged in user uid is: $userId');
if (isUpdating) {
customer.updatedAt = Timestamp.now();
await customerRef.document(userId).updateData(customer.toMap());
print('updated customer with id: ${customer.id}');
} else {
customer.createdAt = Timestamp.now();
DocumentReference documentReference = await customerRef.document(userId);
// add(customer.toMap());
customer.id = documentReference.documentID;
print('created customer successfully with id: ${customer.id}');
await documentReference.setData(customer.toMap(), merge: true);
addCustomer(customer);
}
notifyListeners();
}
我如何继续从仅由 currentUser() 创建的 firebase 读取客户数据,因为 documentID/customer.id 现在等于 currentUser() 登录的 userId?
这是我迄今为止尝试过的:
getCustomers(CustomerNotifier customerNotifier) async {
String userId = (await FirebaseAuth.instance.currentUser()).uid;
print('Current logged in user uid is: $userId');
QuerySnapshot snapshot = await Firestore.instance
.collection('customers')
.where('id', isEqualTo: userId)
.orderBy('created_at', descending: true)
.getDocuments();
List<Customer> _customerList = [];
snapshot.documents.forEach((document) {
Customer customer = Customer.fromMap(document.data);
_customerList.add(customer);
});
customerNotifier.customerList = _customerList;
}
//customer_screen.dart //这使用一个ListView.builder来显示currentUser()创建的所有客户
class CustomersScreen extends StatefulWidget {
static String id = 'customers';
@override
_CustomersScreenState createState() => _CustomersScreenState();
}
class _CustomersScreenState extends State<CustomersScreen> {
bool showSpinner = true;
bool _isInit = true;
@override
void initState() {
if (_isInit) {
showSpinner = true;
} else {
showSpinner = false;
}
CustomerNotifier customerNotifier =
Provider.of<CustomerNotifier>(context, listen: false);
customerNotifier.getCustomers(customerNotifier);
super.initState();
}
@override
Widget build(BuildContext context) {
CustomerNotifier customerNotifier = Provider.of<CustomerNotifier>(context);
Future<void> _resfreshList() async {
customerNotifier.getCustomers(customerNotifier);
}
return Scaffold(
drawer: DrawerClass(),
appBar: AppBar(
title: Text(
'All customers',
style: kAppBarTextStyle,
),
backgroundColor: kAppBarColour,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
customerNotifier.currentCustomer = null;
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
return CustomerFormScreen(isUpdating: false);
}));
},
child: Icon(Icons.add),
backgroundColor: kThemeIconColour,
),
// body: showSpinner
// ? Center(child: CircularProgressIndicator())
body: RefreshIndicator(
child: Consumer<CustomerNotifier>(
builder: (context, customer, child) {
return customer == null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
PaddingClass(bodyImage: 'images/empty.png'),
SizedBox(
height: 20.0,
),
Text(
'You don\'t have any customer',
style: kLabelTextStyle,
),
],
)
: Padding(
padding: const EdgeInsets.only(top: 50.0),
child: ListView.separated(
itemBuilder: (context, int index) {
return Card(
margin: EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
elevation: 15.0,
color: Colors.white70,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
height: 100.0,
child: Icon(
FontAwesomeIcons.userCircle,
color: kThemeIconColour,
size: 50.0,
),
),
SizedBox(width: 20.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(' ${customer.customerList[index].firstName}' +
' ${customer.customerList[index].lastName}'),
SizedBox(
height: 8.0,
),
Text(
' ${customer.customerList[index].phoneNumber}'),
SizedBox(
height: 8.0,
),
Text(
' ${customer.customerList[index].email}'),
],
),
GestureDetector(
onTap: () {
customerNotifier.currentCustomer =
customerNotifier.customerList[index];
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) {
return CustomerDetailsScreen();
}));
},
child: Icon(
FontAwesomeIcons.caretDown,
color: kThemeIconColour,
),
),
],
),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 20.0,
);
},
itemCount: customerNotifier.customerList.length,
),
);
},
),
onRefresh: _resfreshList,
),
);
}
}
谢谢。
【问题讨论】:
-
您可以发布您当前尝试检索单个客户数据的代码吗?
-
我刚刚发布了我尝试过的内容。
-
我在这里看到的是您有一个名为 Users 的集合,该集合中的文档由 uid 命名。您是否只想获取单个 uid 的信息?如果是这样,那么您希望使用 documentSnapshot。但是,您的函数看起来正在寻找客户的集合 -> 这意味着您可能需要第二个集合,因此它看起来像:客户(集合)-> uid(文档)-> thisUsersItems(集合)跨度>
-
我正在寻找一系列客户。所以基本上,当前登录用户创建的所有客户。我已经将每个客户文档的 documentId 设置为与 currentUser() uid 相同。我不确定我是否得到你最后评论的后半部分。你能用一个示例/更多解释来解释吗?谢谢。
-
好的,有道理!执行此操作的方法不止一种,您已根据客户文档中的值选择执行此操作。让我更新我的答案
标签: firebase flutter google-cloud-firestore firebase-authentication flutter-dependencies