Home > database >  What's the difference between the two `SetState()` usages?
What's the difference between the two `SetState()` usages?

Time:12-05

Just wondering if there is any difference between:

      // == Add all picked idoes to the mix table
      setState(() {
        Future.forEach(result, (asset) async {
          final video = await MixTableVideo.create(original: asset);
          videos.add(video);
        });
      });

and:

      // == Add all picked idoes to the mix table

      Future.forEach(result, (asset) async {
          final video = await MixTableVideo.create(original: asset);
          videos.add(video);
        });

      setState(() {});

CodePudding user response:

In the first code snippet, the setState function is being called with a callback that runs the Future.forEach function, which iterates over the elements in the result list and adds each element to the videos list using the MixTableVideo.create function.

In the second code snippet, the Future.forEach function is run outside of the setState callback. This means that the videos list will be updated before the setState function is called, but the UI will not be updated until after setState is called.

CodePudding user response:

Before we can use state, we need to declare a default set of values for the initial state. This can be done by either creating a state object in the constructor or directly within the class.

CodePudding user response:

Finally I did this which fires a UI update at each video addition:

      // == Add all picked videos to the mix table
      Future.forEach(result, (asset) async {
        final video = await MixTableVideo.create(original: asset);
        setState(() {
          videos.add(video);
        });
      });
  • Related