Home > database >  Flutter cannot use URL variable inside Image.network widget
Flutter cannot use URL variable inside Image.network widget

Time:01-27

Im trying to get url from cloud firebase and then use it in Image.network but it doesn't work.. When i hardcode the url inside Image.network it works.. the variable did get the url as the data.

I get an error from image.dart - ImageStreamListener throw error.

this is my code:


class _MemoryCardState extends State<MemoryCard> {
  Map<String, dynamic> photos = {};

  Future getPhoto() async {
    photos.clear();
    var db = FirebaseFirestore.instance.collection('photos');
    await db.doc(widget.id).get().then((DocumentSnapshot snapshot) {
      photos = snapshot.data() as Map<String, dynamic>;
    });
  }

  @override
  Widget build(BuildContext context) {
    var deviceWidth = MediaQuery.of(context).size.width;
    var deviceHeight = MediaQuery.of(context).size.height;

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Card(
          semanticContainer: true,
          clipBehavior: Clip.antiAliasWithSaveLayer,
          elevation: 10,
          color: Theme.of(context).colorScheme.surfaceVariant,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          child: SizedBox(
            width: deviceWidth * 0.8,
            height: deviceWidth * 0.35,
            child: InkWell(
              splashColor: Colors.blue.withAlpha(30),
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => const Memory()));
              },
              child: Stack(
                children: [
                  FutureBuilder(
                      future: getPhoto(),
                      builder: (context, snapshot) {
                        String url = photos['url'].toString();
                        return Hero(
                            tag: 'image',
                            child: Image.network(
                              url,
                              fit: BoxFit.cover,
                              width: deviceWidth * 0.8,
                              color: Colors.white.withOpacity(0.5),
                              colorBlendMode: BlendMode.modulate,
                            ));
                      }),
                ],
              ),
            ),
          ),
        ),
        SizedBox(height: deviceHeight * 0.2),
      ],
    );
  }
}



CodePudding user response:

The error you are encountering is likely caused by the fact that the url variable is not yet available when the Image.network widget is first rendered. The FutureBuilder widget is used to handle this issue, but it is not being used correctly in your code.

A FutureBuilder widget should be used to rebuild the widget tree when the future completes.

You should move the FutureBuilder outside of the InkWell and Stack widgets.

FutureBuilder(
future: getPhoto(),
builder: (context, snapshot) {
    if (snapshot.hasData) {
      String url = photos['url'].toString();
      return InkWell(
          splashColor: Colors.blue.withAlpha(30),
          onTap: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => const Memory()));
          },
          child: Stack(
            children: [
              Hero(
                  tag: 'image',
                  child: Image.network(
                    url,
                    fit: BoxFit.cover,
                    width: deviceWidth * 0.8,
                    color: Colors.white.withOpacity(0.5),
                    colorBlendMode: BlendMode.modulate,
                  )),
            ],
          ),
        );
    } else {
        return CircularProgressIndicator();
    }
},

);

Also, it will be a better practice to check if the snapshot hasData before trying to access the url.

Also, you can use await keyword to wait for the data retrieval to complete, before using the url value in the Image.network.

CodePudding user response:

give the url which you found from firebase. If you used URI as DataType in firebase then it is the problem.

  • Related