Search code examples
androidfluttersetstatestatelesswidget

Flutter call setState() to update UI in another class


I am trying to call a setState when a button is pressed so the ui can show the new list but even using functions i cant use setState or it will give me the error saying im calling setState inside a constructor.

This is my code for the statlessWidget:

class _MessageCard extends StatelessWidget {
final Mensagem message;
final int messageLenght;
final List<Mensagem> messageList;
var i;
_MessageCard(
  {@required this.message,
  @required this.messageLenght,
  @required this.messageList});

@override
Widget build(BuildContext context) {
return Center(
    child: Container(
  width: 600,
  child: InkWell(
    child: Container(
      width: 900,
      color: Colors.grey[200],
      child: Padding(
        padding: const EdgeInsets.fromLTRB(12, 0, 12, 0),
        child: Center(
          child: Container(
            width: 600,
            child: Column(
              children: <Widget>[
                ListTile(
                  leading: CircleAvatar(
                    child: Icon(
                      Icons.notifications,
                      color: Colors.red[400],
                    ),
                    backgroundColor: Colors.grey[200],
                  ),
                  title: Text(
                    (this.message.vDescricao ?? '').trim(),
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.black,
                    ),
                  ),
                  subtitle: Text(
                    (this.message.vData ?? '').trim() +
                        '   ' +
                        (this.message.vHora ?? '').trim(),
                    style: TextStyle(
                      color: Colors.red[400],
                      fontSize: 13,
                    ),
                  ),
                  trailing: FlatButton(
                      child: Text(
                        Translations.of(context)
                            .trans('finishmessageshort'),
                      ),
                      onPressed: () => _showDeleteAlertMessage(
                          this.message.vNumero, context)),
                ),
                Divider(
                  color: Colors.black54,
                ),
              ],
            ),
          ),
        ),
      ),
    ),
  ),
 ));
}

Future _showDeleteAlertMessage(String id, BuildContext context) {
return showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: new Text(
          Translations.of(context).trans('finishmessage') + '?',
        ),
        actions: <Widget>[
          FlatButton(
              child: new Text(
                Translations.of(context).trans('closealert'),
              ),
              onPressed: () {
                Navigator.of(context).pop();
              }),
          FlatButton(
            child: new Text(("Ok")),
            onPressed: () =>
                {_deleteMessage(id), Navigator.of(context).pop()},
          )
        ],
      );
    });
}

_deleteMessage(String id) async {
for (i = 0; i < this.messageLenght; i++) {
  if (this.messageList[0].vNumero == this.message.vNumero) {
    this.messageList.removeAt(i);
    _HomePageState().mensagemRepo.confirmMessage(this.message.vNumero);
    await _HomePageState()._getMessages();
    return this.messageList;
   }
  }
 }
}

And this is my _getMessages()

_getMessages() async {
setState(() {
  _loading = true;
  _errorMsg = '';
});

try {
  _messages = await mensagemRepo.getMessages();

  print('loaded messages: ${_messages?.length}');
} catch (e) {
  _errorMsg = e.toString();
}

setState(() {
  _loading = false;
});

}

How can i make it so i can use this setState?

Thank you for your time and attention

Edit: Now updates List but not UI, because im not able to set HomePage state from MessageCard


Solution

  • I managed to make it work, by making both classes into one and calling a function to draw the messagecards, thank you all for your help and attention