Home > OS >  How to connected String to futur of Futurbuilder with flutter?
How to connected String to futur of Futurbuilder with flutter?

Time:11-12

I try to use a FuturBuilder to build a widget after that my initStat load data from firebase.

At the init I call a function to receive url from firebase

string url;

   
load_url() async {
url=  await FirebaseStorage.instance.refFromURL('gs://XXXXX-XXXXX.appspot.com/XXXX.jpg').getDownloadURL();
 }

After that I try to build a widget to display the url

CachedNetworkImage(
placeholder: (context, url) => Center(child:CircularProgressIndicator(),) ,
imageUrl: '$url',
);

I can't use CachedNetworkImage directly because url is load after init build. So i try to Build UI after receive URL

I try to use FuturBuilder like that

FutureBuilder(
        future: "$url",
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none: return new Text('');
            case ConnectionState.waiting: return new Text('');
            default:
              if (snapshot.hasError)
                return new Text('Error: ${snapshot.error}');
              else
                return CachedNetworkImage(
                  placeholder: (context, url) => Center(child:CircularProgressIndicator(),) ,
                  imageUrl: '$url',
                );
          }
        },
      );

But I can't write future: "$url", I have this error

The argument type 'String' can't be assigned to the parameter type 'Future<dynamic>?'.

CodePudding user response:

Change your FutureBuilder to this:

FutureBuilder<String>(
    future: FirebaseStorage.instance.refFromURL('gs://XXXXX-XXXXX.appspot.com/XXXX.jpg').getDownloadURL(),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none: return new Text('');
        case ConnectionState.waiting: return new Text('');
        default:
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          else
            String imageUrl = snapshot.data ?? "";
            return CachedNetworkImage(
              placeholder: (context, url) => Center(child:CircularProgressIndicator(),) ,
              imageUrl: imageUrl,
            );
      }
    },
  );
  • Related