【问题标题】:how to refresh ListView.builder flutter如何刷新 ListView.builder 颤动
【发布时间】:2020-05-12 14:46:41
【问题描述】:

向列表添加项目时如何刷新我的 ListView.builder?

ListView.builder(
      itemCount: propList.length,
      scrollDirection: Axis.horizontal,
      shrinkWrap: true,
      itemBuilder: (context,index)=> Text(propList[index]),
    )

我的按钮是

FlatButton(onPressed: (){propList.add('text');}, child: Text('add'))

【问题讨论】:

    标签: list listview flutter dart builder


    【解决方案1】:

    假设您已扩展 StatefulWidget,则每次更改状态时都必须调用 setState。例如:

    setState(() { propList.add('text'); });
    

    这是一个简单的例子:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) => MaterialApp(home: MyList());
    }
    
    class MyList extends StatefulWidget {
      @override
      _MyListState createState() => _MyListState();
    }
    
    class _MyListState extends State<MyList> {
      List<String> propList = [];
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('My List'),
          ),
          body: ListView.builder(
            itemCount: propList.length,
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemBuilder: (context,index)=> Text(propList[index]),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () => setState(() => propList.add('text')),
            child: Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    }
    

    【讨论】:

    • 非常感谢,这很有效,并感谢您提供示例。
    • 删除呢? setState(() { propList.remove(widget.propName); });那没用
    • remove 方法采用您要删除的确切对象。或者您可以致电removeLast()@Husamuldeen
    • 如何在 STATELESS 小部件上进行强制刷新..
    • @VrajendraSinghMandloi 您可以使用提供程序包并使用未来的构建器。在 Cosumer 中包装 ListView 构建器
    【解决方案2】:

    你可以在 onPressed 中试试:setState(() { propList.length; });

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 2021-05-26
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 2021-12-22
      • 2021-11-19
      • 1970-01-01
      相关资源
      最近更新 更多