ListView.custom constructor Null safety
- {Key? key,
- Axis scrollDirection = Axis.vertical,
- bool reverse = false,
- ScrollController? controller,
- bool? primary,
- ScrollPhysics? physics,
- bool shrinkWrap = false,
- EdgeInsetsGeometry? padding,
- double? itemExtent,
- Widget? prototypeItem,
- required SliverChildDelegate childrenDelegate,
- double? cacheExtent,
- int? semanticChildCount,
- DragStartBehavior dragStartBehavior = DragStartBehavior.start,
- ScrollViewKeyboardDismissBehavior keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
- String? restorationId,
- Clip clipBehavior = Clip.hardEdge}
Creates a scrollable, linear array of widgets with a custom child model.
For example, a custom child model can control the algorithm used to estimate the size of children that are not actually visible.
This ListView uses a custom SliverChildBuilderDelegate to support child
reordering.
class MyListView extends StatefulWidget {
const MyListView({super.key});
@override
State<MyListView> createState() => _MyListViewState();
}
class _MyListViewState extends State<MyListView> {
List<String> items = <String>['1', '2', '3', '4', '5'];
void _reverse() {
setState(() {
items = items.reversed.toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView.custom(
childrenDelegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return KeepAlive(
data: items[index],
key: ValueKey<String>(items[index]),
);
},
childCount: items.length,
findChildIndexCallback: (Key key) {
final ValueKey<String> valueKey = key as ValueKey<String>;
final String data = valueKey.value;
return items.indexOf(data);
}
),
),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: () => _reverse(),
child: const Text('Reverse items'),
),
],
),
),
);
}
}
class KeepAlive extends StatefulWidget {
const KeepAlive({
required Key key,
required this.data,
}) : super(key: key);
final String data;
@override
State<KeepAlive> createState() => _KeepAliveState();
}
class _KeepAliveState extends State<KeepAlive> with AutomaticKeepAliveClientMixin{
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return Text(widget.data);
}
}
Implementation
const ListView.custom({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
this.itemExtent,
this.prototypeItem,
required this.childrenDelegate,
super.cacheExtent,
super.semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
}) : assert(childrenDelegate != null),
assert(
itemExtent == null || prototypeItem == null,
'You can only pass itemExtent or prototypeItem, not both',
);