I had a function in my CustomerNotifier class that reads all customers as a list from Firebase as below:
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;
}
I have another function to updates or creates a new customer and saves to Firebase as below:
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();
}
With both methods above, I used to successfully read and write customer data to my Firebase. However, I am trying to only read data created and updated by the currently signed in User. So suggestions from other stackoverflow threads, I've been advised to set my customer.id to userId, where userId == currentUser().uid. I can successfully write to my DB using an updated version of my updateCustomer as below:
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();
}
How do I proceed to read customer data from firebase only created by currentUser() since documentID/customer.id is now equals to userId fo the currentUser() logged in?
Here's what I've tried so far:
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 //this uses a ListView.builder to display all customers created by 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,
),
);
}
}
Thanks.