Reputation: 7024
Here's my code:
networkConnectivity.listen((value) async {
print("Before: $value");
await Future.delayed(const Duration(seconds: 5));
print("Later: $value");
if (!value) {
...
} else {
..
}
});
Let's say the listener gets triggered when there's no internet and Before
value is false
. But even if Before
value is already changed to true
within 5 seconds, Later
remains false.
Why am I not getting the updated value in this situation? What's the workaround?
Upvotes: 0
Views: 1245
Reputation: 1715
Based on your latest response where you want to show a dialog once the listener calls the provided callback with false (no connection) and the callback won't be called with the value true within 5 seconds, the following approach might be what you want:
Timer noConnectivityTimer;
...
networkConnectivity.listen((value) async {
if (!value && (noConnectivityTimer == null || !noConnectivityTimer.isActive)) {
noConnectivityTimer = Timer(Duration(seconds: 5), () => showDialog(...));
} else {
noConnectivityTimer?.cancel();
...
}
},
);
What i did: making use of the Timer
class where i can define a Duration
where a callback (defined right after) will be called once the given duration has been reached - we will show the dialog there. But if our listener callback gets a value which is true, indicating we have a connection again, we want to cancel any running Timer
so the dialog is only shown when we received a false value initially and no true value within 5 seconds. You might want to edit this as you need it in your app, this is just an example!
Upvotes: 2
Reputation: 4526
A variable's value won't change unless something changes it. In the code you provide, nothing change the value of 'value' between your two prints.
Presumably, what will happen when the connectivity changes, is that your code block will run again, with a new value in the 'value' variable.
Upvotes: 0