Undefitied
Undefitied

Reputation: 747

flutter setState: how to update with array?

I have an array of small objects which is used to display List. What I'm doing now:

final _wordsList = <Word>[];
String triggerRerender;

getSharedText() async {
    var sharedData = await platform.invokeMethod("getSharedText");
    if (sharedData != null) {
      _wordsList.add(Word(sharedData));

      setState(() {
        triggerRerender = sharedData;
      });
    }
  }

and that feels wild. Shouldn't I be triggering rerender by changing array, not by some "trigger" primitive?

Upvotes: 0

Views: 3605

Answers (1)

dumazy
dumazy

Reputation: 14435

You don't need to have a triggerRenderer, I think.

Here's what the docs say:

Whenever you change the internal state of a State object, make the change in a function that you pass to setState

Just update the data inside of the setState function:

final _wordsList = <Word>[];

getSharedText() async {
  var sharedData = await platform.invokeMethod("getSharedText");
  if (sharedData != null) {
    setState(() {
      _wordsList.add(Word(sharedData))
    });
  }
}

Upvotes: 4

Related Questions