I want to refresh my Text "ganzerchat" but it dont works with how i do it
thats my Chat Class (StatefulWidget) i tryed with setstate but nothing happens everytime.
I opened the Chat from the main.dart
List chatverlauf = [];
Future getDataFromYourApi() async {
List<String> tmp = [];
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body) as Map<String, dynamic>;
chatverlauf.clear();
ganzerChat = "";
extractedData.forEach((id, data) {
tmp.add(data["name"] ": " data["text"]);
//print(data["name"] ": " data["text"]);
});
return tmp;
}
Future<void> loadChat() async{
chatverlauf = await getDataFromYourApi();
setState(() {
ganzerChat = chatverlauf.join("\n");
print(ganzerChat);
});
}
return Scaffold(
appBar: AppBar(
title: Text("Chat"),
),
body: Container(
alignment: Alignment.center,
child:
Column(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
Container(
margin: EdgeInsets.only(right: 20, bottom: 50),
alignment: Alignment.centerRight,
child: Text(
ganzerChat,
textAlign: TextAlign.right,
)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
width: 300,
color: Colors.grey,
child: TextField(controller: eingabecontroller)),
ElevatedButton(
child: Text("Senden"),
onPressed:()async{
await loadChat();
},
),
],
),
]),
),
);
}
maybe anyone here have the same problem and can help me
CodePudding user response:
I found the problem. It was because I had the methods below the Widget build. I put it above then it worked!
Sorry for the time waste, I thank you very much anyway.
CodePudding user response:
Try to create a new function to set chatverlauf values. Something like this: getDataFromYourApi():
Future<void> loadChat() async{
ganzerChat = "";
chatverlauf = await getDateFromYourApi();
for(int i=0;i<chatverlauf.lenght;i ){
ganzerChat = ganzerChat chatverlauf[i] "\n";
}
setState(() {
ganzerChat = ganzerChat "";
});
}
In your ElevatedButton:
ElevatedButton(
child: Text("Senden"),
onPressed: ()async{
await loadChat();
}
),
CodePudding user response:
You don't need to use a for
cycle to join the array
of Strings
. Just do a join
with the \n
as the separator:
setState(() {
ganzerChat = chatverlauf.join("\n")
});
CodePudding user response:
Now, in the function getDataFromYourApi() try this:
Future <List<String>> getDataFromYourApi() async {
...
}
CodePudding user response:
Maybe I set my Statefull widget incorrectly.