我已经创建了method
和widge
t,现在我的代码可以正常工作,因为数据是static
,我想在按下添加按钮时在add new item
中选择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:
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
,而不是StatelessWidget
,以便我们可以利用setState()
方法。
首先,定义一个类成员变量。您可以将其放在类的顶部,或其他任何位置,只要它不在函数内即可。
List<Widget> _listOfWidgets = [];
第二,让我们修改您的FAB(浮动操作按钮)代码:
FloatingActionButton(
onPressed: () {
print("fab clicked");
_addItemToList(); // new method
},
child:Text("+"),
backgroundColor: Colors.blue,
);
现在让我们定义将使用我们的类成员变量的新方法。
_addItemToList() {
List<Widget> tempList = _listOfWidgets; // defining a new temporary list which will be equal to our other list
tempList.add(Text("I'm an added item!"));
setState(() {
_listOfWidgets = tempList; // this will trigger a rebuild of the ENTIRE widget, therefore adding our new item to the list!
});
}
让我们修改您现有的代码以使用我们的新代码:
Widget listSection = Container(
margin: EdgeInsets.only(top: 210),
child: ListView(
children: [
Column(
children: _listOfWidgets,
),
],
),
);
你去!