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
  });
Share:
284
tyler.morton
Author by

tyler.morton

Updated on January 01, 2023

Comments

  • tyler.morton
    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
    tyler.morton over 2 years
    Thank you for your answer. What do you mean by force the function after returning?
  • novol
    novol over 2 years
    I did edit answer
  • novol
    novol over 2 years
    I mean this code in initState void initState() { super.initState(); AndroidAlarmManager.initialize(); IsolateNameServer.registerPortWithName( port.sendPort, isolateName, ); port.listen((_) async => await _incrementCounter()); }
  • tyler.morton
    tyler.morton over 2 years
    Okay thank you that worked but just with Navigator.of(context).push. Is it at also possible to get the same result with Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => My2Site(),),(_) => false); ?
  • novol
    novol over 2 years
  • novol
    novol over 2 years
    But why delete the previous screens if you want to return to them?