Flutter - Hero widget child Image url from Firebase

Viewed 260

I am trying to create a Hero widget which has a child Image.network()

Hero(
 tag: 'headerView',
 transitionOnUserGestures: true,
 child: Image.network(
   headerPhoto,
   fit: BoxFit.cover,
 ),
)

The image url -headerPhoto- is being fetched from Firestore asynchronously, therefore, I assume I have to put this Hero widget inside a FutureBuilder.

FutureBuilder(
  builder: (context, snapshot) {
  ...
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasData) {
        String headerPhoto = snapshot.data['headerPhoto'];
        return Scaffold(
          body:GestureDetector(
            onTap: () {
              _showPage('headerView', headerPhoto);
            },
            child: Hero(
              tag: 'headerView',
              transitionOnUserGestures: true,
              child: Image.network(
                headerPhoto,
                width: MediaQuery.of(context).size.width,
                fit: BoxFit.cover,
              ),
            ),
          ),
        )
      } 
    }
    ...
  },
  future: _fetchHeaderPhoto(userData),
);

When I use Hero widget inside the FutureBuilder like above, first animation works like it should. But when I navigate back from PageView -which only have Hero widget in it- the animation does not work. On the other hand, while I was trying Hero widget with hardcoded strings like:

Hero(
  tag: 'headerView',
  transitionOnUserGestures: true,
  child: Image.network(
    'https://picsum.photos/200/300',
    fit: BoxFit.cover,
  ),
)

First animation and second animation both worked perfectly. Is this problem occurs because I use FutureBuilder? If it isn't what is the problem?

Thanks in advance.

1 Answers

That's because FutureBuilder fetches data every time whole first widget is rebuild. To prevent that, create new function which gets headerPhoto and update the state of the first widget. Call this function inside initState. That should do the trick.

Related