Search code examples
androidflutterdartfor-loopwidget

How can I print the for loop values in the button widget to the application screen?-Flutter


I'm learning Flutter. I have a problem. When I press the button, I want the values in the for loop to be printed on the application screen.

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("For Döngüsü"),
        ),
        body: Column(
          children: [
            ElevatedButton(
              child: Text("Sayilar"),
              onPressed: () {
                for (int i = 0; i < 15; i++) {
                  Text("$i");
                }
              },
            ),
          ],
        ));
  }
}

Solution

  • You can create a list on state class and widget on it.Then I am using ListView.builder to show the widget on app screen.

    List<Widget> items = [];
    @override
    Widget build(BuildContext context) {
      return Scaffold(
          appBar: AppBar(
            title: Text("For Döngüsü"),
          ),
          body: Column(
            children: [
              ElevatedButton(
                child: Text("Sayilar"),
                onPressed: () {
                  for (int i = 0; i < 15; i++) {
                    items.add(Text("$i"));
                  }
                  setState(() {}); //update the ui
                },
              ),
              Expanded(
                  child: ListView.builder(
                      itemCount: items.length,
                      itemBuilder: (context, index) => items[index]))
            ],
          ));
    }