首页 > 解决方案 > 单击时添加新的 ListTile 项

问题描述

我已经创建method并且widget,现在我的代码工作正常,因为数据是static,我想在ListTile按下添加按钮时添加新项目。

方法:

Card listSectionMethod(String title, String subtitle, IconData icon) {
  return new Card(
    child: ListTile(
      title: Text(
        title,
        style: TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: Text(subtitle),
      trailing: Icon(
        icon,
        color: Colors.blue,
      ),
    ),
  );
}

小部件:

Widget listSection = Container(

   margin: EdgeInsets.only(top: 210),
              child: ListView(
                children: [
                   Column(
                   children: [
                      listSectionMethod("TITLE 1", "hello i am subtitle one",Icons.forward),
                      listSectionMethod("TITLE 2", "hello i am subtitle two",Icons.forward),  
                   ],
                  ),
                ],),
);

按钮:

FloatingActionButton(
 onPressed:()
 {
    print("clicked"); //i want to add new item from here, when i press on click
 }, 

 child:Text("+"),
 backgroundColor: Colors.blue,
),
);

标签: flutterflutter-layout

解决方案


要添加新项目,您必须执行以下操作:

假设你的屏幕是一个 StatefulWidget

class SomePage extends StatefulWidget {
  @override
  _SomePageState createState() => _SomePageState();
}

class _SomePageState extends State<SomePage> {
     var _listSection = List<Widget>();

     @override
     void initState() {
        super.initState();
        // Here initialize the list in case it is required
        _listSection.add(
          listSectionMethod("TITLE 1", "hello i am subtitle one", Icons.forward),
        );
        _listSection.add(
          listSectionMethod("TITLE 2", "hello i am subtitle two", Icons.forward),
        );
     }
 } 

小部件:

    Widget listSection() {
        return Container(
          margin: EdgeInsets.only(top: 210),
          child: ListView(
            children: [
              Column(
                children: this._listSection, // ----> Add this
              ),
            ],
          ),
        );
     }

按钮:

    FloatingActionButton(
          onPressed: () {
            setState(() {
               // Here we add a new item to the list
              _listSection.add(
                listSectionMethod("New TITLE", "hello from click", Icons.forward),
              );
            });
          },
          child: Text("+"),
          backgroundColor: Colors.blue,
       );

推荐阅读