Flutter - setState not updating inner Stateful Widget

AndroidDartFlutterDart Async

Android Problem Overview


Basically I am trying to make an app whose content will be updated with an async function that takes information from a website, but when I do try to set the new state, it doesn't reload the new content. If I debug the app, it shows that the current content is the new one, but after "rebuilding" the whole widget, it doesn't show the new info.

Edit: loadData ( ) method, basically read a URL with http package, the URL contains a JSON file whose content changes every 5 minutes with new news. For example a .json file with sports real-time scoreboards whose scores are always changing, so the content should always change with new results.

class mainWidget extends StatefulWidget
{    
  State<StatefulWidget> createState() => new mainWidgetState();
}

class mainWidgetState extends State<mainWidget>
{

  List<Widget> _data;
  Timer timer;

  Widget build(BuildContext context) {
     return new ListView(
              children: _data);
  }

  @override
  void initState() {
    super.initState();
    timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) async {
      String s = await loadData();
      this.setState(() {
        _data = <Widget> [new childWidget(s)];
      });
      });
  }
}

class childWidget extends StatefulWidget {
  childWidget(String s){
    _title = s;
  }

  Widget _title;

  createState() => new childState();
}

class childState extends State<gameCardS> {

  Widget _title;

  @override
  Widget build(BuildContext context) {
    return new GestureDetector(onTap: foo(),
       child: new Card(child: new Text(_title));

  }

  initState()
  {
    super.initState();
    _title = widget._title;
  }
}

Android Solutions


Solution 1 - Android

This should sort your problem out. Basically you always want your Widgets created in your build method hierarchy.

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(new MaterialApp(home: new Scaffold(body: new MainWidget())));

class MainWidget extends StatefulWidget {
	@override
	State createState() => new MainWidgetState();
}

class MainWidgetState extends State<MainWidget> {

	List<ItemData> _data = new List();
	Timer timer;

	Widget build(BuildContext context) {
		return new ListView(children: _data.map((item) => new ChildWidget(item)).toList());
	}

	@override
	void initState() {
		super.initState();
		timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) async {
			ItemData data = await loadData();
			this.setState(() {
				_data = <ItemData>[data];
			});
		});
	}


	@override
	void dispose() {
		super.dispose();
		timer.cancel();
	}

	static int testCount = 0;

	Future<ItemData> loadData() async {
		testCount++;
		return new ItemData("Testing #$testCount");
	}
}

class ChildWidget extends StatefulWidget {

	ItemData _data;

	ChildWidget(ItemData data) {
		_data = data;
	}

	@override
	State<ChildWidget> createState() => new ChildState();
}

class ChildState extends State<ChildWidget> {

	@override
	Widget build(BuildContext context) {
		return new GestureDetector(onTap: () => foo(),
			child: new Padding(
				padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0),
				child: new Card(
					child: new Container(
						padding: const EdgeInsets.all(8.0),
						child: new Text(widget._data.title),
					),
				),
			)
		);
	}

	foo() {
		print("Card Tapped: " + widget._data.toString());
	}
}

class ItemData {
	final String title;

	ItemData(this.title);

	@override
	String toString() {
		return 'ItemData{title: $title}';
	}
}

Solution 2 - Android

This was really giving me headache and no Google results were working. What finally worked was so simple. In your child build() assign the value to the local variable before you return. Once I did this everything worked with subsequent data loads. I even took out the initState() code.

Many thanks to @Simon. Your answer somehow inspired me to try this.

In your childState:

@override
Widget build(BuildContext context) {
_title = widget._title; // <<< ADDING THIS HERE IS THE FIX
return new GestureDetector(onTap: foo(),
   child: new Card(child: new Text(_title));

}

Hopefully this works in your code. For me, I use a Map for the entire JSON record passed in, rather than a single String, but that should still work.

Solution 3 - Android

The Root issue explained

  • initState(), for the child widget, is called only once when the Widget is inserted into the tree. Because of this, your child Widget variables will never be updated when they change on the parent widget. Technically the variables for the widgets are changing, you are just not capturing that change in your state class.

  • build() is the method that gets called every time something in the Widget changes. This is the reason @gregthegeek solution works. Updating the variables inside the build method of your child widget will ensure they get the latest from parent.

Works

class ChildState extends State<ChildWidget> {
    late String _title;
    @override
    Widget build(BuildContext context) {
        _title = widget._title; // <==== IMPORTANT LINE
        return new GestureDetector(onTap: () => foo(),
            child: new Text(_title),
        );
    }
}

Does not work

(It will not update when _title changes in parent)

class ChildState extends State<ChildWidget> {
    late String _title;

    @override
    void initState() {
      super.initState();
      _title = widget._title; // <==== IMPORTANT LINE
    }

    @override
    Widget build(BuildContext context) {
        return new GestureDetector(onTap: () => foo(),
            child: new Text(_title),
        );
    }
}

Solution 4 - Android

I'm unsure why this happens when calling setState(...) in an async function, but one simple solution is to use:

WidgetsBinding.instance.addPostFrameCallback((_) => setState(...));

instead of just setState(...)

Solution 5 - Android

This fixed my issue... If you have an initial value to be assigned on a variable use it in initState()

Note : Faced this issue when I tried to set initial value inside build function.

@override
  void initState() {
    count = widget.initialValue.length; // Initial value
    super.initState();
  }

Solution 6 - Android

don't use a future within a future; use different function that will return each future individually like this

 List<Requests> requestsData;
 List<DocumentSnapshot> requestsDocumentData;
 var docId;



  @override
  void initState() {
    super.initState();

    getRequestDocs();
  }

  Future<FirebaseUser> getData() {
    var _auth = FirebaseAuth.instance;
    return _auth.currentUser();
  }

  getRequestDocs() {
    getData().then((FirebaseUser user) {
      this.setState(() {
        docId = user.uid;
      });
    });

    FireDb()
        .getDocuments("vendorsrequests")
        .then((List<DocumentSnapshot> documentSnapshots) {
      this.setState(() {
        requestsDocumentData = documentSnapshots;
      });
    });

    for (DocumentSnapshot request in requestsDocumentData) {
      this.setState(() {
        requestsData.add(Requests(
            request.documentID,
            request.data['requests'],
            Icons.data_usage,
            request.data['requests'][0],
            "location",
            "payMessage",
            "budget",
            "tokensRequired",
            "date"));
      });
    }
  }

you can create individual functions for

  FireDb().getDocuments("vendorsrequests")
            .then((List<DocumentSnapshot> documentSnapshots) {
          this.setState(() {
            requestsDocumentData = documentSnapshots;
          });
        });

and

  for (DocumentSnapshot request in requestsDocumentData) {
          this.setState(() {
            requestsData.add(Requests(
                request.documentID,
                request.data['requests'],
                Icons.data_usage,
                request.data['requests'][0],
                "location",
                "payMessage",
                "budget",
                "tokensRequired",
                "date"));
          });
        }

I found that the use of

this

with setState is must

Solution 7 - Android

first check whether it is a stateless or stateful widget,and if the class is stateless then make it to a stateful widget and try adding a code after closing the setState(() { _myState = newValue; });

Solution 8 - Android

In my case, it was just defining the state as a class property and not a local variable in the build method

Doing this -

  List<Task> tasks = [
    Task('Buy milk'),
    Task('Buy eggs'),
    Task('Buy bread'),
  ];
  @override
  Widget build(BuildContext context) {
  
    return ListView.builder(
      itemBuilder: (context, index) => TaskTile(
...

instead of this -

 @override
  Widget build(BuildContext context) {
  List<Task> tasks = [
    Task('Buy milk'),
    Task('Buy eggs'),
    Task('Buy bread'),
  ];
  
    return ListView.builder(
      itemBuilder: (context, index) => TaskTile(
...

Solution 9 - Android

Found the best solution. If you are using a stateless widget you can't use set state, so just convert the stateless widget to statefull widget

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJes&#250;s Mart&#237;nView Question on Stackoverflow
Solution 1 - AndroidSimonView Answer on Stackoverflow
Solution 2 - AndroidgregthegeekView Answer on Stackoverflow
Solution 3 - Androideriel marimonView Answer on Stackoverflow
Solution 4 - Androidcaneva20View Answer on Stackoverflow
Solution 5 - AndroidAbhin Krishna KAView Answer on Stackoverflow
Solution 6 - AndroidRashid IqbalView Answer on Stackoverflow
Solution 7 - AndroidKe1212View Answer on Stackoverflow
Solution 8 - AndroidPiyushView Answer on Stackoverflow
Solution 9 - AndroidAbdulmas empireView Answer on Stackoverflow