0

I want to show a dialog in whole app when a intent is triggered. For this, I add onNewIntent listener in android and invoke a flutter method:

@Override
protected void onNewIntent(Intent intent) {
    if (intent.getAction().equals("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {
        methodChannel.invokeMethod("method_name", null);
    }
    super.onNewIntent(intent);
}

and in the main.dart, in initState method set a methodCallHandler for this method:

  @override
  void initState() {
    super.initState();
    AndroidApi.platform.setMethodCallHandler((call) async {
      debugPrint("here");
      if (call.method == "method_name") {
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) => const LoadingDialog(),
        );
      }
    });
  }

In the console, I see the onNewIntent log and "method_name" is called. and I see the "here" log in my console. but the dialog is not shown. Can you find the problem?

Mohamadamin
  • 564
  • 5
  • 16
  • try `debugPrint(call.method)` or make a debugPrint inside the if, to at least confirm it gets inside the if – Ivo Sep 26 '22 at 11:14
  • @Ivo I tried this. It gets inside the if. – Mohamadamin Sep 26 '22 at 11:26
  • It can be related to the `context` you pass to `showDialog`. By the time `showDialog` gets called, the current context my be different from what you passed in `initState`. You could try to use `await` before `showDialog` to wait for the future to complete. – Peter Koltai Sep 26 '22 at 12:59
  • @PeterKoltai I tried this. But still not working ... – Mohamadamin Oct 01 '22 at 07:07

1 Answers1

0

try this,

 if (call.method == "method_name") {
  Future.delayed(Duration(seconds: 1), () {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => const LoadingDialog(),
    );
  });
}
Dharini
  • 700
  • 7
  • 20