0
I have a function retornaDescricao()
which makes an http request and edits the variable controller with the received value. However, the value is only changed when I press the Elevatedbutton for the second time() .
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class AgregarUsuario extends StatefulWidget {
@override
_AgregarUsuarioState createState() => _AgregarUsuarioState();
}
class _AgregarUsuarioState extends State<AgregarUsuario> {
TextEditingController controlNombre = new TextEditingController();
TextEditingController controlTelefono = new TextEditingController();
TextEditingController controlEmail = new TextEditingController();
TextEditingController controlDescricao = new TextEditingController();
Future retornaDescricao() async {
var resposta;
http.Response response;
response = await http
.get(Uri.parse("http://192.168.2.5/pruebas/obterDescricao.php"));
resposta = json.decode(response.body);
var lista = resposta;
String descricao = lista[0]["nombre"];
controlDescricao.text = descricao;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("AGREGAR USUARIO"),
),
body: Container(
padding: EdgeInsets.all(10.0),
child: Center(
child: Column(
children: <Widget>[
TextField(
controller: controlNombre,
decoration:
InputDecoration(labelText: "Código de barras - EAN"),
),
TextField(
controller: controlTelefono,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: "Quantidade"),
),
Padding(padding: EdgeInsets.all(16.0)),
ElevatedButton(
onPressed: () {
//agregarUsuario();
setState(() {
retornaDescricao();
print("texto recebido: " + controlDescricao.text);
});
agregarUsuario();
//Navigator.pushReplacementNamed(context, '/');
},
child: Text("Adicionar à impressão"),
),
Container(
height: 35.0,
child: Text(
controlDescricao.text,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 30.0),
))
],
),
),
),
);
}
void agregarUsuario() {
//var url = "http://192.168.0.11/pruebas/agregarUsuario.php";
if (controlNombre.text == null || controlNombre.text == "") {
} else {
http.post(Uri.parse("http://192.168.2.5/pruebas/agregarUsuario.php"),
body: {
"nombre": controlNombre.text,
"telefono": controlTelefono.text,
"email": controlEmail.text,
});
}
}
}
Console return:
Restarted application in 1.139ms.
I/flutter ( 9135): texto recebido:
2
I/flutter ( 9135): texto recebido: 789000000000000