简体   繁体   中英

How to run a code in whole flutter app (every screen of the app)

I want to run a block of code in whole flutter app(in every screens).

Scenario: I have an intent in android layer for attaching usb device to the android device. And I want to show a dialog when the intent is triggered. I try to write this on MyApp initState block, but dialog is not shown, or I get this error:

Unhandled Exception: No MaterialLocalizations found.
MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.

see this question for not showing my dialog.

But now, My question is how to run a block of code in every screen of flutter app?

It's not wrong to put it in the initState of MyApp, but doing this you are running the code before the app has rendered the first frame, thus not having the localization inheritedWidget that is made available by the MaterialApp. You can solve by wrapping the intent trigger with the addPostFrameCallback in the WidgetsBinding, like this:

   WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  AndroidApi.platform.setMethodCallHandler((call) async {
    debugPrint("here");
    if (call.method == "method_name") {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) => const LoadingDialog(),
      );
    }
  });
});

(I got the code from the other question)

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