Flutter Isolate doesn't go do setState after navigate to a other page and back
284
initState
is not called again after returning, try to force the function you want after returning
something like that
Navigator.of(context)
.push(MaterialPageRoute(
builder: (context) => YourScreen№2(),
))
.then((value) {
Foo() <- your func
});
Author by
tyler.morton
Updated on January 01, 2023Comments
-
tyler.morton over 1 year
Hello I have a badge with a counter and whenever I start my Android Alarm Manager it should increase the counter and also update the UI live. I do this with Isolate. Everything works fine but when I go to a new page route and then go back the SetState is not executed anymore. Where is my error?
int _counter = 0; String isolateName = 'isolate'; final ReceivePort port = ReceivePort(); static SendPort uiSendPort; @override void initState() { super.initState(); AndroidAlarmManager.initialize(); IsolateNameServer.registerPortWithName( port.sendPort, isolateName, ); port.listen((_) async => await _incrementCounter()); } Future<void> _incrementCounter() async { print('Increment counter!'); // Ensure we've loaded the updated count from the background isolate. await prefs.reload(); if (!mounted) return; setState(() { print("geht in die SetState"); _counter++; }); } /// ///This is in my Callback for my Android Alarm Manager... final prefs = await SharedPreferences.getInstance(); int currentCount = prefs.getInt(countKey) ?? 0; await prefs.setInt(countKey, currentCount + 1); // This will be null if we're running in the background. uiSendPort ??= IsolateNameServer.lookupPortByName('isolate'); uiSendPort?.send(null);
-
tyler.morton over 2 yearsThank you for your answer. What do you mean by force the function after returning?
-
novol over 2 yearsI did edit answer
-
novol over 2 yearsI mean this code in
initState
void initState() { super.initState(); AndroidAlarmManager.initialize(); IsolateNameServer.registerPortWithName( port.sendPort, isolateName, ); port.listen((_) async => await _incrementCounter()); }
-
tyler.morton over 2 yearsOkay thank you that worked but just with
Navigator.of(context).push
. Is it at also possible to get the same result withNavigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => My2Site(),),(_) => false);
? -
novol over 2 yearsseems ye, more here api.flutter.dev/flutter/widgets/Navigator/…
-
novol over 2 yearsBut why delete the previous screens if you want to return to them?