0

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?

1 Answer 1

4

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))
    });
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

That has appeared so, thank you. Funny thing, that it also works, if I do: _wordsList.add(Word(sharedData)); setState(() { });. Hence seems like setState() doesn't look on what happens inside it's callback
setState triggers the build() function. You can always set state and trigger the function later, but it's not recommended, because of the asynchronous way in which these things are executed, I think

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.