简体   繁体   中英

try to update value of variable when app is in resumed state in flutter

I am trying to update value of dynamiclink at the time of when app is in resumed state but still its display null value. how i update value of variable in app is in resumed state even without kill the app.

for example in dynamic link scan one qr code and redirect to our app again app is background and i scan second qr code at that time value of dynamic link is not updated

    String dynamiclink;    
    void didChangeAppLifecycleState(AppLifecycleState state) {
            if (state == AppLifecycleState.resumed) {
              setState(() {
                dynamiclink = " ";
              });
              _timerLink = new Timer(const Duration(milliseconds: 850), () {
                _retrieveDynamicLink();
              });
            }else{
              _retrieveDynamicLink();
            }
         }

    // here i am passing value in variable named dynamiclink

     Future<void> _retrieveDynamicLink() async {
        final PendingDynamicLinkData data =
        await FirebaseDynamicLinks.instance.getInitialLink();
        final Uri deepLink = data?.link;
        dynamiclink = deepLink.toString();
     }

Extend your class with WidgetBindingObserver

class MyApp extends WidgetBindingObserver implement these two functions, where you add and dispose the widget binding observers, binding observers are notified of different application events

@override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

And finally

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
   
            if (state == AppLifecycleState.resumed) {
              setState(() {
                dynamiclink = " ";
              });
              _timerLink = new Timer(const Duration(milliseconds: 850), () {
                _retrieveDynamicLink();
              });
            }else{
              _retrieveDynamicLink();
            }
         }

  }

This shall work.

For more information:

  1. https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html
  2. didChangeAppLifecycleState doesn't work as expected
  3. https://medium.com/pharos-production/flutter-app-lifecycle-4b0ab4a4211a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM