Flutter catch changes

Viewed 45

is there a way to make a widget(for example Text) value linked to a variable that is inside a for loop and make it changed every time the variable changes inside the loop, i want to make the Widget Text to change as well, for example:

int count;
for(var i = 0; i <= 100; i++){
count = i;
}

the widget code:

Text('Loop: ' + count.toString());

im looking for the output to be something like Text('Loop: 1') and every time the loop goes on the output will be Text('Loop (1,2,3,4,5....)') but the the problem is with this code, the Text widget waits until the loop ends and gives me the last count number. is there a way to make the text widget changes without waiting for loop to end? Thanks.

1 Answers

If your loop is running on the same thread, a call like setState won't take place until after the function is over. What you need to do is launch the loop on another thread. This example should help you understand what I mean (it uses the threading package [https://pub.dev/packages/threading])

class _MyHomePageState extends State<MyHomePage> {
  int counter = 0;
  @override
  void initState() {
    var thread = new Thread(count);
    thread.start();
    super.initState();
  }

  void count() async {
    for (int i = 0; i < 100; i++) {
      setState(() {
        counter = i;
      });
      await Thread.sleep(1000);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("$counter"),
      ),
    );
  }
}

However, this would be a good time to learn about Streams, StreamControllers, and the many state management libraries we have out there, because you'd normally handle something like this through those.

Note: If you have null safety enabled, the threading package is not null safe, so you'd have to add --no-sound-null-safety to your flutter run command to make it work.

Related