【问题标题】:Clear ListView in Flutter在 Flutter 中清除 ListView
【发布时间】:2023-04-09 16:58:01
【问题描述】:

我构建了将用户名存储在列表中并在 ListView 中查看的应用程序,但我想在按下清除按钮后清空 ListView 以不显示任何内容。

我添加了 names.clear() 但似乎它清除了不在视图中的幕后列表。

有什么方法可以实现吗?

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

【问题讨论】:

    标签: listview flutter dart


    【解决方案1】:

    这里应该使用setState()方法告诉widget配置发生变化,所以需要修改引用widget。

      setState(() {
           names.clear();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      相关资源
      最近更新 更多