I am use Firestore transaction for avoid race condition of add more than 1 user to chat. If transaction timeout, I show error dialog.
But when I move this logic to Model2
with ChangeNotifier
(and Provider
) it now show error:
Unhandled Exception: A Model2 was used after being disposed. Once you have called dispose() on a Model2, it can no longer be used.
(No issue with Firestore transaction. This is expected):
PlatformException(9, Transaction failed all retries.: Every document read in a transaction must also be written in that transaction., null)
It seem ChangeNotifier
is call dispose()
too early?
This mean it not allow me to handle error of race condition because it is already dispose.
Model:
class Model2 extends ChangeNotifier {
...
bool userAdded;
Future<bool> addUser() async {
try {
await Firestore.instance.runTransaction((transaction) async {
DocumentSnapshot chatRoomDocSnapshot =
await transaction.get(chatRoomDocRef);
bool userInChat = await chatRoomDocSnapshot[‘userInChat'];
if (userInChat == false) {
await transaction.update(chatRoomDocSnapshot.reference, {
‘userInChat': true,
});
}
});
await chatUserRef.setData({
‘User’: user,
});
userAdded = true;
notifyListeners();
} catch (e) {
print(e);
userAdded = false;
notifyListeners();
}
return userAdded;
}
Provider (in stateful widget):
fetchData();
return ChangeNotifierProxyProvider<Model1, Model2>(
initialBuilder: (_) => Model2(),
builder: (_, model1, model2) => model2
..string = model1.string,
),
child: Consumer<Model2>(
builder: (context, model2, _) =>
...
await model2.addUser();
...
Anyone know solution?
Thanks!
Update:
Issue is not throw if I remove fetchData();
from build
method before ChangeNotifierProxyProvider
.
But why is this fix the issue?