0

I have a question about how to return the results of a For loop to a list of widgets in Flutter.

My code where the cycle is executed is the following:

enter image description here

In this code example, I want to generate a list from the results of the for loop. The display should show:

  • Number 1
  • Number 2
  • Number 3
  • Number 4
  • Number 5

But you can only see the "Numer 1"

Code example:

import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 255, 32, 47);
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text("List Numbers")
        ),
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return listNumbers();
  }
  
  Widget listNumbers(){
    for (int i = 0; i < 5; i++) {
      return Text('Number ${i + 1}', style: TextStyle(fontSize: 25));
    }
  }
}
1
  • Please post your code within the question instead of as a linked image. Commented Jul 4, 2020 at 17:28

1 Answer 1

2

You can try using ListView.

Widget listNumbers(){
  List<Text> numList= [];
  for (int i = 0; i < 5; i++) {
    numList.add(Text('Number ${i + 1}', style: TextStyle(fontSize: 25));
  }
  return ListView(children: numList);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I thank you very much, your proposed code has worked for me. Regards!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.