我正在实施聊天,当项目从列表中删除时出现问题。如果我从 CustomScrollView 的底部删除多个项目,则滚动位置会根据删除项目的高度之和向上偏移。我该如何预防?
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
List<int> list = List.generate(30, (i) => i + 1).reversed.toList();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() {
list.removeRange(0, 5);
});
},
),
),
body: CustomScrollView(
reverse: true,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
alignment: Alignment.center,
color: Colors.blue[200 + list[index] % 4 * 100],
height: 100,
child: Text('Item: ${list[index]}'),
);
},
childCount: list.length,
),
),
],
),
);
}
}