Post adding data to my firestore database, using a
Future<void> addNewData(BuildContext context, String data) {
return showModalBottomSheet(
context: context,
builder: (context) {
return Scaffold(
// add data in a text field and using a button post to firestore
);
}
);
}
I want to get updated FutureProvider which is defined as
@riverpod
class FetchData extends _$FetchData {
@override
Future<List<Data>> build() async {
List<Data> _myList = [];
final snapshot = await FirebaseFirestore.instance
.collection('data')
.get();
for (var doc in snapshot.docs) {
_myList.add(Data.fromMap(doc));
}
return _myList;
}
}
Also, a function is used to manually set a TextField’s value and is notified of this change through a SecondProvider. This provider reads the state of fetchDataProvider in performOperation function.
@riverpod
class SecondProvider extends _$SecondProvider {
@override
String? build() {
return '';
}
void performOperation(String data) {
final AsyncValue<List<Data>> myList = ref.read(fetchDataProvider);
String uid = '';
if (myList.value != null && myList.hasValue) {
int checked = 0;
if (myList.value!.length > 0) {
for (var item in myList.value!) {
if (item == data) {
uid = item;
state = uid;
break;
}
checked = checked + 1;
/// If data did not match to any of the myList items from base then set to empty
if (checked == myList.value!.length) {
state = uid;
}
}
} else {
state = uid;
}
}
}
}
So, in the UI code, inside a onPressed of a button, I do
addNewData(context, dataController!.text).then((_) {
ref.invalidate(fetchDataProvider);
ref.read(SecondProvider.notifier).performOperation(dataController!.text);
});
Since ref.invalidate
takes time, ref.read
after that does give wrong state of ''
;
Above code is simplified version, this will make more sense when Data is a class and one of its field is generated by database. That db generated field is needed in second Provider.
How to wait for fetch data provider to get updated with new value then do performOperation? or Am I doing something conceptually wrong.
Thanks
1