【问题标题】:Flutter Isolate doesn't go do setState after navigate to a other page and back导航到其他页面并返回后,Flutter Isolate 不会执行 setState
【发布时间】:2021-10-06 09:54:44
【问题描述】:

您好,我有一个带有计数器的徽章,每当我启动我的 Android 警报管理器时,它应该增加计数器并实时更新 UI。我用隔离来做到这一点。一切正常,但是当我转到新的页面路由然后返回时,不再执行 SetState。我的错误在哪里?

  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);

【问题讨论】:

    标签: android flutter dart setstate dart-isolates


    【解决方案1】:

    initState返回后不再调用,返回后尝试强制执行你想要的函数

    类似的东西

    Navigator.of(context)
      .push(MaterialPageRoute(
         builder: (context) => YourScreen№2(),
      ))
      .then((value) {
        Foo() <- your func
      });
    

    【讨论】:

    • 感谢您的回答。返回后强制函数是什么意思?
    • 我确实编辑了答案
    • 我的意思是initStatevoid initState() { super.initState(); AndroidAlarmManager.initialize(); IsolateNameServer.registerPortWithName( port.sendPort, isolateName, ); port.listen((_) async =&gt; await _incrementCounter()); }中的这段代码
    • 好的,谢谢你的工作,但只是 Navigator.of(context).push。是否也可以使用Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) =&gt; My2Site(),),(_) =&gt; false); 获得相同的结果?
    猜你喜欢
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2019-11-03
    • 2013-05-11
    • 1970-01-01
    • 2022-01-06
    • 2020-07-29
    • 2018-11-17
    相关资源
    最近更新 更多