flutter - 单击时添加新的 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,
),
);
解决方案
要添加新项目,您必须执行以下操作:
假设你的屏幕是一个 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,
);
推荐阅读
- javascript - 逗号是否仅适用于javascript中的console.log以将变量与字符串连接起来?
- python-3.x - 如何根据第二个参数对输出文件进行排序?
- database - Laravel BD::rollBack 不要在我的代码中工作
- python - Jupyter Notebook Pycharm 2019 IDE中的Python导入错误
- angular7 - 在 ag-grid 中使用自定义单元格渲染器时无法读取未定义的属性“导航”
- umbraco - 获取子项的图像 ID
- javascript - 如何在 cytoscape.js 中显示子节点的同时隐藏复合节点
- hyperledger-fabric - 在 Hyperledger Fabric 中提交交易时出错
- java - Graphite 正在汇总数据
- r - 你什么时候使用警告(味精)?