text
stringlengths
1
474
list or a list with very large amounts of data.
<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 = [];
@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.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.builder(
itemCount: widgets.length,
itemBuilder: (context, position) {
return getRow(position);
},
),
);
}
}<code_end>
Instead of creating a ListView, create a ListView.builder
that takes two key parameters: the initial length of the list,
and an ItemBuilder function.The ItemBuilder function is similar to the cellForItemAt
delegate method in an iOS table or collection view,
as it takes a position, and returns the
cell you want rendered at that position.Finally, but most importantly, notice that the onTap() function
doesn’t recreate the list anymore, but instead .adds to it.<topic_end>
<topic_start>
Creating a scroll view
In UIKit, you wrap your views in a ScrollView that
allows a user to scroll your content if needed.In Flutter the easiest way to do this is using the ListView widget.
This acts as both a ScrollView and an iOS TableView,
as you can lay out widgets in a vertical format.
<code_start>@override
Widget build(BuildContext context) {
return ListView(
children: const <Widget>[
Text('Row One'),
Text('Row Two'),
Text('Row Three'),
Text('Row Four'),
],
);
}<code_end>
For more detailed docs on how to lay out widgets in Flutter,
see the layout tutorial.<topic_end>
<topic_start>
Gesture detection and touch event handling
This section discusses how to detect gestures
and handle different events in Flutter,
and how they compare with UIKit.<topic_end>
<topic_start>
Adding a click listener
In UIKit, you attach a GestureRecognizer to a view to
handle click events.
In Flutter, there are two ways of adding touch listeners:If the widget supports event detection, pass a function to it,
and handle the event in the function. For example, the
ElevatedButton widget has an onPressed parameter:
<code_start>@override
Widget build(BuildContext context) {