我需要在 CustomScrollView 底部对齐消息(通常在所有聊天中都会这样做)。这是我的代码:
class TempScreen extends StatefulWidget {
TempScreen({Key? key}) : super(key: key);
@override
State<TempScreen> createState() => _TempScreenState();
}
class _TempScreenState extends State<TempScreen> {
List<String> messages = [
"msg1", "msg2", "msg3", "msg4", "msg5", "msg6", "msg7", "msg8", "msg9", "msg10"
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AppBar'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Scrollbar(
child: CustomScrollView(
//scrollDirection: Axis.vertical,
//shrinkWrap: true,
slivers: <Widget>[
SliverFillRemaining(
hasScrollBody: false,
// fillOverscroll: true, // Set true to change overscroll behavior. Purely preference.
child: Column(
children: [
Expanded(
child: Container(
color: Colors.green,
child: SizedBox(height: 1,),
),
),
for (var msg in this.messages) ...[
Text(msg, style: TextStyle(fontSize: 30),)
]
],
),
)
],
),
),
),
Padding(
padding: const EdgeInsets.all(10),
child: TextField(
textAlign: TextAlign.left,
decoration: InputDecoration(
hintText: 'Message',
contentPadding: EdgeInsets.all(10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
isDense: true,
),
keyboardType: TextInputType.multiline,
maxLines: 4,
minLines: 1,
//controller: textController,
textInputAction: TextInputAction.send,
onSubmitted: (value) {
this.setState(() {
this.messages.add(value);
});
},
),
)
],
)
);
}
}
当应用程序启动时,前十条消息将按预期显示(在底部对齐):
添加下一条消息时出现问题:
您会看到,在添加消息
11
和消息 12
后显示键盘时,看不到 CustomScrollView
中的最后一条消息。换句话说,当添加消息12
时,用户无法看到消息11
。问题是 CustomScrollView 在显示键盘时应该向下滚动。谁能说一下怎么做吗?
尝试在自定义滚动条中添加反向属性。它会反转滚动条的方向。
CustomScrollView(
reverse: true,
...
)
查看此链接以获取更多信息:
https://api.flutter.dev/flutter/widgets/ScrollView/reverse.html
你可以尝试用 padding 包裹你的小部件,并设置
viewInsets.bottom
当移动设备的键盘可见时 viewInsets.bottom 对应键盘顶部。
查看此文档了解详细信息:https://api.flutter.dev/flutter/widgets/MediaQueryData/viewInsets.html
body: Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
.......
Flutter 为此制作了一个视频: