1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import 'package:flutter/material.dart';
6
7/// Flutter code sample for a [ListView.custom] using the `findChildIndexCallback` argument.
8void main() => runApp(const ListViewExampleApp());
9
10class ListViewExampleApp extends StatelessWidget {
11 const ListViewExampleApp({super.key});
12
13 @override
14 Widget build(BuildContext context) {
15 return const MaterialApp(home: ListViewExample());
16 }
17}
18
19class ListViewExample extends StatefulWidget {
20 const ListViewExample({super.key});
21
22 @override
23 State<ListViewExample> createState() => _ListViewExampleState();
24}
25
26class _ListViewExampleState extends State<ListViewExample> {
27 List<String> items = <String>['1', '2', '3', '4', '5'];
28
29 void _reverse() {
30 setState(() {
31 items = items.reversed.toList();
32 });
33 }
34
35 @override
36 Widget build(BuildContext context) {
37 return Scaffold(
38 body: SafeArea(
39 child: ListView.custom(
40 childrenDelegate: SliverChildBuilderDelegate(
41 (BuildContext context, int index) {
42 return KeepAliveItem(data: items[index], key: ValueKey<String>(items[index]));
43 },
44 childCount: items.length,
45 findChildIndexCallback: (Key key) {
46 final ValueKey<String> valueKey = key as ValueKey<String>;
47 final String data = valueKey.value;
48 final int index = items.indexOf(data);
49 if (index >= 0) {
50 return index;
51 }
52 return null;
53 },
54 ),
55 ),
56 ),
57 bottomNavigationBar: BottomAppBar(
58 child: Row(
59 mainAxisAlignment: MainAxisAlignment.center,
60 children: <Widget>[
61 TextButton(onPressed: () => _reverse(), child: const Text('Reverse items')),
62 ],
63 ),
64 ),
65 );
66 }
67}
68
69class KeepAliveItem extends StatefulWidget {
70 const KeepAliveItem({required Key super.key, required this.data});
71
72 final String data;
73
74 @override
75 State<KeepAliveItem> createState() => _KeepAliveItemState();
76}
77
78class _KeepAliveItemState extends State<KeepAliveItem> with AutomaticKeepAliveClientMixin {
79 @override
80 bool get wantKeepAlive => true;
81
82 @override
83 Widget build(BuildContext context) {
84 super.build(context);
85 return Text(widget.data);
86 }
87}
88

Provided by KDAB

Privacy Policy
Learn more about Flutter for embedded and desktop on industrialflutter.com