我正在开发一个flutter应用程序。目前,我没有太多,但我的问题是,如何通过单击appBar中的加号图标将卡添加到列表(ListView(中?代码:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Todo'),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
tooltip: 'Add a todo card',
onPressed: () {`
},
),
],
),
这不是整个课堂,而是你需要看到的东西。我有我的应用程序栏和图标按钮。这就是我的一张卡片的样子,它是一个占位符:
children: <Widget>[
Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.album),
title: Text('The Enchanted Nightingale'),
subtitle:
Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('BUY TICKETS'),
onPressed: () {},
),
const SizedBox(width: 8),
TextButton(
child: const Text('LISTEN'),
onPressed: () {},
),
const SizedBox(width: 8),
],
),
],
),
),
我想把这种卡片(自定义(添加到ListView(主体(中。
实现这一目标的步骤:
- 创建一个无状态小部件,将
TodoCard
提取为一个单独的小部件 - 创建一个小部件列表,将您的
TodoCard
小部件保存在TodoScreen
中 - 在
initState
中添加一个TodoCard
,以便在构建TodoScreen
后渲染一个 - 当按下添加待办事项卡时,将
TodoCard
添加到创建的小部件列表中,并调用setState
来触发重建 - 使用排列运算符在
ListView
中呈现TodoCard
小部件的列表
我以您的代码为例添加了一个演示:
TODOCARD WIDGET
// create a stateless widget to extract your TodoCard
class TodoCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.album),
title: Text('The Enchanted Nightingale'),
subtitle: Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
child: const Text('BUY TICKETS'),
onPressed: () {},
),
const SizedBox(width: 8),
TextButton(
child: const Text('LISTEN'),
onPressed: () {},
),
const SizedBox(width: 8),
],
),
],
),
);
}
}
TODOSCREEN
class TodoScreen extends StatefulWidget {
@override
_TodoScreenState createState() => _TodoScreenState();
}
class _TodoScreenState extends State<TodoScreen> {
// create a list of widget to hold your TodoCard widgets
List<Widget> _allCards = [];
@override
void initState() {
super.initState();
// add a single TodoCard so one will be rendered once the page is built
_allCards.add(TodoCard());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Todo'),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
tooltip: 'Add a todo card',
onPressed: () {
// when the add todo card is pressed, add a TodoCard to the list of widgets created and call setstate to trigger a rebuild
setState(() {
_allCards.add(TodoCard());
});
},
),
],
),
body: ListView(
children: [
// reder the list of TodoCard widgets using the spread operator
..._allCards,
],
),
);
}
}