Home > Software design >  Flutter web app should launch a URL and then navigate to another screen
Flutter web app should launch a URL and then navigate to another screen

Time:12-30

I am working on a Flutter project.

I have an issue only when launching the web app.

There is a button that opens a URL on another browser tab:

  ElevatedButton(
                onPressed:(){
                  _launchUrl;
                  Navigator.pushAndRemoveUntil(
                      context,
                      MaterialPageRoute(builder: (BuildContext context) => MyHomePage()),
                          (Route<dynamic> route) => false

                  );
                },
                child: Text('pagarpedido'.tr()),
              ),

Here you have _launchUrl():

Future<void> _launchUrl() async {
  if (!await launchUrl(_url)) {
    throw 'Could not launch $_url';
  }
}

The issue is that when clicking on the button, the app is pushing MyHomePage(), but not opening the expected URL on another browser tab.

Removing the Navigator.pushAndRemoveUntil function from the code, when the button is clicked, the expected URL is opened on another browser tab.

What I need is ot click the button and after that to open the URL on another browser tab and the web app should show MyHomePage().

CodePudding user response:

Try using the await keyword to wait for the _launchUrl() function to complete before navigating to the MyHomePage page. Here's how you can modify your code:

ElevatedButton(
  onPressed: () async {
    await _launchUrl();
    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(builder: (BuildContext context) => MyHomePage()),
      (Route<dynamic> route) => false
    );
  },
  child: Text('pagarpedido'.tr()),
),

This way, the _launchUrl() function will be called first, and once it completes, the app will navigate to the MyHomePage page.


I am also not sure why the _launchUrl() function is like that but if you are using a package, you can just use this function below to open a new tab without any package and also doesn't require the function to be a Future.

import 'dart:html' as html;

void _launchUrl() {
  html.window.open(url, 'Your App name');
}
  • Related