Home > Software engineering >  setState doesn't update on first time - Flutter
setState doesn't update on first time - Flutter

Time:10-10

The setState method in my app is triggered when a submit button to a form is clicked

child: GestureDetector(
       onTap: () {
          if (_key.currentState!.validate()) {
              setState(() {
                  sendMessage(dropdownValue,_valueController.text);
              });
          }
       },

The function that is called:

sendMessage(int user, String text) async {
    final sendMessageUri =
        Uri.https('mysecrethater.herokuapp.com', '/api/send/');
    var response = await http.post(
      sendMessageUri,
      headers: {
        "Access-Control-Allow-Origin": "*",
        'Content-Type': 'application/json',
        'Accept': '*/*'
      },
      body: jsonEncode({
        'user': user,
        'value': text,
      }),
    );
    if (response.statusCode == 201) {
      message = 'The message was sent successfully';
    } else if (response.statusCode == 406) {
      message = 'Positivity detected. Message not allowed.';
    } else {
      message = 'Some error happened, please try again later.';
    }
}

The message variable is a global variable linked to a Text(); The Text(); widget updates only if I click the button two times, while the sendMessage function is called and evaluated normally.

CodePudding user response:

First change your sendMessage() to this:

Future<String> sendMessage(int user, String text) async {
    final sendMessageUri =
        Uri.https('mysecrethater.herokuapp.com', '/api/send/');
    var response = await http.post(
      sendMessageUri,
      headers: {
        "Access-Control-Allow-Origin": "*",
        'Content-Type': 'application/json',
        'Accept': '*/*'
      },
      body: jsonEncode({
        'user': user,
        'value': text,
      }),
    );
    if (response.statusCode == 201) {
      return 'The message was sent successfully';
    } else if (response.statusCode == 406) {
      return 'Positivity detected. Message not allowed.';
    } else {
      return 'Some error happened, please try again later.';
    }
  }

then use it like this:

onTap: () async{
 if (_key.currentState!.validate()) {
    String result = await sendMessage(dropdownValue, _valueController.text);
    setState(() {
        message  = result
    });
 }
},
  • Related