当用户单击应用栏中的"+"号时,如何将卡片添加到列表视图?



我正在开发一个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(主体(中。

实现这一目标的步骤:

  1. 创建一个无状态小部件,将TodoCard提取为一个单独的小部件
  2. 创建一个小部件列表,将您的TodoCard小部件保存在TodoScreen
  3. initState中添加一个TodoCard,以便在构建TodoScreen后渲染一个
  4. 当按下添加待办事项卡时,将TodoCard添加到创建的小部件列表中,并调用setState来触发重建
  5. 使用排列运算符在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,
],
),
);
}
}

相关内容

  • 没有找到相关文章