I can't see all your code, but there is a trick you can do that will avoid having to add extra code. It involves reversing the data in the list of messages and setting to true
the reverse
property of the ListView
. This will make the messages move up as new messages come in.
You reverse the original list, you set to true
the reverse
property of the ListView
, and when you add messages to your List you use messages.insert(0, newMessage)
to add it to the top (now bottom because of inversion), instead of of messages.add
.
class Issue65846722 extends StatefulWidget {
@override
_Issue65846722State createState() => _Issue65846722State();
}
class _Issue65846722State extends State<Issue65846722> {
List<String> messages = [
'message 1',
'message 2',
'message 3',
].reversed.toList();
TextEditingController textEditingController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('StackOverflow'),
),
floatingActionButton: Align(
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.only(top: 100.0),
child: FloatingActionButton(
// To simulate an incoming message from another source that is not
// the local TextField
child: Icon(Icons.message),
onPressed: () => newMessage('new message'),
),
),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
reverse: true,
itemCount: messages.length,
itemBuilder: (context, index){
return Container(
child: Text(messages[index]),
);
},
),
),
Divider(color: Colors.black,),
TextFormField(
controller: textEditingController,
onFieldSubmitted: (_) => submitMessage()
),
],
),
);
}
void submitMessage(){
newMessage(textEditingController.text);
textEditingController.clear();
}
void newMessage(String newMessage){
setState(() {
messages.insert(0, newMessage);
});
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…