skip to Main Content

I have a problem in flutter when I add a new element to the list and I call setState, the list is updated but the screen is not.
I tried calling the setState after addText() but it doesn’t work also.

This is my code:

import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  @override
  _TestScreenState createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  List<Widget> testList = [
    Text('data'),
  ];

  void addText() {
    setState(() {
      testList.add(
        Text('data'),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: ListView(
                children: testList,
              ),
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    addText();
                  });
                },
                child: Text('Click'))
          ],
        ),
      ),
    );
  }
}

2

Answers


  1. You can use listView like this

    ListView.builder(
      shrinkWrap: true,
      itemCount: testList.length,
      itemBuilder(context, index) {
        return testList[index];
      }
    )
    
    void addText() {
          testList.add(
            Text('data'),
          );
      }
    
    Login or Signup to reply.
  2. Your bug is because of calling setState twice, there is no need to call it in addText():

    import 'package:flutter/material.dart';
    
    class TestScreen extends StatefulWidget {
      @override
      _TestScreenState createState() => _TestScreenState();
    }
    
    class _TestScreenState extends State<TestScreen> {
      List<Widget> testList = [
        Text('data'),
      ];
    
      void addText() {
        testList.add(
          Text('data'),
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          body: SafeArea(
            child: Column(
              children: [
                Expanded(
                  child: ListView(
                    children: testList,
                  ),
                ),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      addText();
                    });
                  },
                  child: Text('Click'),
                ),
              ],
            ),
          ),
        );
      }
    }
    

    happy coding…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search