Search code examples
flutterurlgoogle-cloud-firestorelauncher

Call a URL from Firestore when using URL Launcher Plugin


I'm using the url_launcher plugin and want to call the URL from a Firestore collection, rather than hard coding it to the app.

I have tried numerous methods to do this (Streambuilder etc...) but to no avail. In a very simplistic example, using the standard url_launcher example code below, how could this be achieved?

void main() {
  runApp(Scaffold(
    body: Center(
      child: RaisedButton(
        onPressed: _launchURL,
        child: Text('Show Flutter homepage'),
      ),
    ),
  ));
}

_launchURL() async {
  const url = 'https://flutter.dev'; // HERE IS WHERE I WANT TO CALL THE URL FROM FIRESTORE
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

Solution

  • You can accomplish this using FutureBuilder

    1. You need to create a future that returns the required imageurl from firestore. The following code is based on my firestore structure and you might need to change a few things.

      Future<DocumentSnapshot> geturl(){
      
       final result = FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser.uid).get();
      
       return result;
      }
      
    2. Use FutureBuilder to load 'url` from firestore.

      FutureBuilder(
             future: geturl(),
               builder: (context, snapshot){
      
                 if (snapshot.hasData){
                   final String url = snapshot.data.data()['imageUrl'].toString();
                   return GestureDetector(
                       onTap: () async{
                        await launch(url);
                       },
                       child: Text('Firestore url')
                   );
                 }
                 return Text('loading url');
               }
           )
      

    I have tested this code an it works absolutely fine.