I want to design an application with buttons. The ‘odd numbers’ button will contain a for loop inside such that when clicked, odd numbers will appear on the screen. I’d like to do similarly for even numbers.
> class _MyHomePageState extends State<MyHomePage> { List<Widget>
> items = []; @override Widget build(BuildContext context) {
> return Scaffold(
> appBar: AppBar(
> title: Text("For Loop"),
> ),
> body: Column(
> children: [
> ElevatedButton(
> child: Text('All Numbers'),
> onPressed: () {
> for (int i = 0; i < 10; i++) {
> items.add(Text("$i"));
> }
> setState(() {});
> },
> ),
> ElevatedButton(
> child: Text('Odd Numbers'),
> onPressed: () {
> for (int i = 0; i < 10; i++) {
> if(i%2==1){
> items.add(Text("$i"));
> }
> }
> setState(() {});
> },
> ),
> ElevatedButton(
> child: Text('Even numbers'),
> onPressed: () {
> for (int i = 0; i < 10; i++) {
> if(i%2==0){
> items.add(Text("$i"));
> }
> }
> setState(() {});
> },
> ),
> Expanded(
> child: ListView.builder(
> itemCount: items.length,
> itemBuilder: (context, index) {
> return Container(
> child: Text(index.toString()),
> );
> })),
> ],
> )); } }
2
Answers
First of all, you need to change the type of your list to integer or string
After that, you need to record values (it could be string or integer) instead of Text widgets.
All Numbers
Odd Numbers
Even Numbers
And then show it in ListView
this works:
I didn’t pass the parameter items to the widget but it’s the same , you can even pass it and it still works.
This solution display even and odd widgets on the screen, if you only have to display text labels or button labels refer to the Vadim Popov solution.