1
votes

I'm using the url_launcher package to launch urls in my app.

I have many links that I need to launch with separate buttons.

However when I load my stateless widget it launches the "_launchURL" function and opens up https://www.yahoo.com immediately.

I believe this have something todo with the widget being called when it gets created. But the function inside "onPressed" should not be called before an actual press, right?

class myStateless extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
        children: <Widget>[
            button("Link 1", "https://www.yahoo.com"),
            button("Link 2", "https://www.google.com"),
        ]
    );
  }
}

Widget button(String text, String url) {
    return RaisedButton(
        child: Text(text),
        onPressed: _launchURL(url),
      );
}

_launchURL(url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

I then get the error: type 'Future<dynamic>' is not a subtype of type 'String'

2

2 Answers

3
votes

Ok, You have to just change at your button() creation method like,

onPressed: _launchURL(url) TO onPressed: () => _launchURL(url),

That's it.

1
votes

There are huge difference between _launchURL, and _launchURL(url).

If you set _launchURL(url) at button click event without button pressed method you are calling method, and if you pass _launchURL it passes just instance of method which will execute at call of the button.