In my case I was calling the setState method before the build method had completed the process of building the widgets.
The Issue
You can face this error if you are showing a snackBar or an alertDialog before the completion of the build method, as well as in many other cases. So, in such cases you should use a callback function as shown below:
WidgetsBinding.instance.addPostFrameCallback((_) { // Add Your Code here. });
or you can also use SchedulerBinding which does the same:
SchedulerBinding.instance.addPostFrameCallback((_) { // add your code here. Navigator.push( context, new MaterialPageRoute( builder: (context) => NextPage())); });
The Problem in Your Code
Your code on onPressed:
executes buildlist('button'+index.toString())
and passes the result to onPressed
, but that is not the desired behavior.
// Bad practice onPressed: buildlist('button'+index.toString()),
It should be:
// Correct way onPressed: () => buildlist('button'+index.toString()),
This way a function (closure) is passed to onPressed
, that when executed, calls buildlist()
.