Let’s learn how to generate a list of widgets in flutter. To create a list of widgets in Flutter we can use List.generate() function.
It looks like below
List List.generate(
int length,
Widget Function(int) generator, {
bool growable = true,
})
So you see that it takes length, it means number of objects you wanna create. Then it takes a function, that function should be responsible for generating widgets.
Then as a generator you can just return any kind of Widgets. In our case, we put a Container() inside the List.generator() as a generator
List.generate(
20,
(index) => Container(
child: Text('My title is $index'),
)
)
The above container, you can style as you like. You could any kind of complex operation in it.
The complete code
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final List<Widget> _widget = List.generate(
20,
(index) => Container(
child: Text('My title is $index'),
)
);
return Scaffold(
appBar: AppBar(title: Text("Expand"),),
body: SingleChildScrollView(
child: ExpansionPanelList.radio(
children: _widget.map((e) => ExpansionPanelRadio(
value: e,
headerBuilder: (BuildContext context, bool isExpanded)=>ListTile(
title: Text("My title"),
),
body: e)).toList(),
),
),
);
}
}
We used ExpansionPanelList.radio() to show the generated List. The generated list could be show inside ListView.builder as well.
Since we use the map() function to unpack the list and loop through it, we need to use toList() to convert it to a List again.
stack bata website ka