Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear ListView in Flutter

I build app which stores users names in list and view it in a ListView, but I want to empty the ListView to show nothing after I press Clear button.

I added names.clear() but it seems that it clears the list behind the scenes not in the view.

Any way to achieve this?

class _NameViewListState extends State<NameViewList> {

  final List<String> names = <String>['Ahmed','Nana'];
  TextEditingController nameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          IconButton(
            icon: Icon(Icons.queue, color: Colors.green,),
            onPressed: (){createDialog(context);},
          ),
          Padding(
            padding: EdgeInsets.all(20),
            child: TextField(
              controller: nameController,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Contact Name',
              ),
            ),
          ),
          RaisedButton(
            child: Text('Clear'),
            onPressed: () {
              names.clear();
            },
          ),
          Expanded(
            child: ListView.builder(
              itemCount: names.length,
                itemBuilder: (BuildContext context, int index){
                return Container(
                  height: 50,
                  child: Center(
                    child: Text('${names[index]}'),
                  ),
                );
                }),
          )
        ],
      ),
    );
  }
}
like image 548
Alex Ali Avatar asked Sep 15 '26 16:09

Alex Ali


1 Answers

Here setState() method should be used to tell widget that the configuration change, so needs to modify the reference widgets.

  setState(() {
       names.clear();
    });
like image 143
Jitesh Mohite Avatar answered Sep 18 '26 07:09

Jitesh Mohite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!