Clear ListView in Flutter

Viewed 3291

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]}'),
                  ),
                );
                }),
          )
        ],
      ),
    );
  }
}
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();
    });
Related