Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter web app should launch a URL and then navigate to another screen

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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().

>Solution :

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');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading