text stringlengths 1 474 |
|---|
widgets.add( |
GestureDetector( |
onTap: () { |
developer.log('row tapped'); |
}, |
child: Padding( |
padding: const EdgeInsets.all(10), |
child: Text('Row $i'), |
), |
), |
); |
} |
return widgets; |
} |
@override |
Widget build(BuildContext context) { |
return Scaffold( |
appBar: AppBar( |
title: const Text('Sample App'), |
), |
body: ListView(children: _getListData()), |
); |
} |
}<code_end> |
<topic_end> |
<topic_start> |
Dynamically updating ListView |
In UIKit, you update the data for the list view, |
and notify the table or collection view using the |
reloadData method.In Flutter, if you update the list of widgets inside a setState(), |
you quickly see that your data doesn’t change visually. |
This is because when setState() is called, |
the Flutter rendering engine looks at the widget tree |
to see if anything has changed. |
When it gets to your ListView, it performs an == check, |
and determines that the two ListViews are the same. |
Nothing has changed, so no update is required.For a simple way to update your ListView, |
create a new List inside of setState(), |
and copy the data from the old list to the new list. |
While this approach is simple, |
it is not recommended for large data sets, |
as shown in the next example. |
<code_start>import 'dart:developer' as developer; |
import 'package:flutter/material.dart'; |
void main() { |
runApp(const SampleApp()); |
} |
class SampleApp extends StatelessWidget { |
const SampleApp({super.key}); |
// This widget is the root of your application. |
@override |
Widget build(BuildContext context) { |
return const MaterialApp( |
title: 'Sample App', |
home: SampleAppPage(), |
); |
} |
} |
class SampleAppPage extends StatefulWidget { |
const SampleAppPage({super.key}); |
@override |
State<SampleAppPage> createState() => _SampleAppPageState(); |
} |
class _SampleAppPageState extends State<SampleAppPage> { |
List<Widget> widgets = <Widget>[]; |
@override |
void initState() { |
super.initState(); |
for (int i = 0; i < 100; i++) { |
widgets.add(getRow(i)); |
} |
} |
Widget getRow(int i) { |
return GestureDetector( |
onTap: () { |
setState(() { |
widgets = List.from(widgets); |
widgets.add(getRow(widgets.length)); |
developer.log('row $i'); |
}); |
}, |
child: Padding( |
padding: const EdgeInsets.all(10), |
child: Text('Row $i'), |
), |
); |
} |
@override |
Widget build(BuildContext context) { |
return Scaffold( |
appBar: AppBar( |
title: const Text('Sample App'), |
), |
body: ListView(children: widgets), |
); |
} |
}<code_end> |
The recommended, efficient, |
and effective way to build a list uses a ListView.Builder. |
This method is great when you have a dynamic |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.