setState() does not update Image widget after data is passed back from another screen

756 views Asked by At

I currently have a screen where if you type into a search field it navigates you to a 2nd screen (ImageResults()) that displays images based upon the search keyword. When you select an image on the 2nd screen, the image url is passed back to the 1st screen and the image should be displayed as a preview.

I did a print statement print(image) to check if the 2nd screen successfully passed the url to the 1st screen and it did. However, the image widget is not updating even after calling setState() and keeps displaying the image when image == null is true when the print statement indicates that image is not null and contains the selected image url.

Any thoughts on what's going on? Thanks!

  Widget build(BuildContext context) {
    String? image;
    TextEditingController _searchInputController = TextEditingController();
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            TextField(
              controller: _searchInputController,
              textInputAction: TextInputAction.search,
              onSubmitted: (String keyword) async {
                var data = await getPics(_searchInputController.text);
                final _image = await Navigator.of(context).push(createRoute(
                    ImageResults(_searchInputController.text, data['photos'])));
                setState(() {
                  _searchInputController.text = '';
                  image = _image;
                });
                print(image);
              },
            ),
            image == null
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: Image.asset(
                      'assets/activity.jpg',
                      height: 200,
                      width: MediaQuery.of(context).size.width * .6,
                      fit: BoxFit.cover,
                    ),
                  )
                : ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: Image.network(
                      image!,
                      height: 200,
                      width: MediaQuery.of(context).size.width * .6,
                      fit: BoxFit.cover,
                    ),
                  )
          ],
        ),
      ),
    );
  }  
1

There are 1 answers

2
Roaa On BEST ANSWER

You need to move your variable declarations outside the build function. Because if your image variable is inside the build function, it will be set to null after your setState()

String? image;

Widget build(BuildContext context) {
  //...
}

I'd recommend you do that for your TextEditingController as well