在 flutter 中的构造函数列表上使用 .map 方法
Using the .map method on a list of constructors in flutter
我有一个 class 用于与构造函数的交易。使用构造函数方法,我创建了一个交易列表,目的是遍历这些交易并将其内容显示在卡片中,但是我在尝试使用列表中的 .map 方法时遇到错误。
我收到的错误消息是 无法将元素类型 'List<Map<dynamic, dynamic>>' 分配给列表类型 'Widget'。
我在 [transactions.map((transaction) => {}).toList()]
上有错误
代码如下:
class Hompage extends StatelessWidget {
final List<Transaction> transactions = [
Transaction(
id: 't1',
title: 'First Transaction',
amount: 1000,
date: DateTime.now(),
),
Transaction(
id: 't2',
title: 'Second Transaction',
amount: 500,
date: DateTime.now(),
)
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Event Planner'),
),
body: Column(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
width: double.infinity,
child: Card(
color: Colors.blue,
child: Text('CHART'),
),
),
Column(
// children: [
// (transactions as List<Map<dynamic, dynamic>>)
// .map((transaction) => {})
// .toList()
// ],
children: [transactions.map((transaction) => {}).toList()],
)
],
),
);
}
}
children: [transactions.map((transaction) => {}).toList()]
首先,去掉括号,你现在有一个列表列表:
children: transactions.map((transaction) => {}).toList()
好的,更好,但是由于 children
需要 Widget
类型的元素,您不能只映射到任何内容。
children: transactions.map((transaction) => Text(transaction.title)).toList()
好多了。不过,您可能想要找到比简单 Text
更高级的东西。
我有一个 class 用于与构造函数的交易。使用构造函数方法,我创建了一个交易列表,目的是遍历这些交易并将其内容显示在卡片中,但是我在尝试使用列表中的 .map 方法时遇到错误。
我收到的错误消息是 无法将元素类型 'List<Map<dynamic, dynamic>>' 分配给列表类型 'Widget'。
我在 [transactions.map((transaction) => {}).toList()]
上有错误代码如下:
class Hompage extends StatelessWidget {
final List<Transaction> transactions = [
Transaction(
id: 't1',
title: 'First Transaction',
amount: 1000,
date: DateTime.now(),
),
Transaction(
id: 't2',
title: 'Second Transaction',
amount: 500,
date: DateTime.now(),
)
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Event Planner'),
),
body: Column(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
width: double.infinity,
child: Card(
color: Colors.blue,
child: Text('CHART'),
),
),
Column(
// children: [
// (transactions as List<Map<dynamic, dynamic>>)
// .map((transaction) => {})
// .toList()
// ],
children: [transactions.map((transaction) => {}).toList()],
)
],
),
);
}
}
children: [transactions.map((transaction) => {}).toList()]
首先,去掉括号,你现在有一个列表列表:
children: transactions.map((transaction) => {}).toList()
好的,更好,但是由于 children
需要 Widget
类型的元素,您不能只映射到任何内容。
children: transactions.map((transaction) => Text(transaction.title)).toList()
好多了。不过,您可能想要找到比简单 Text
更高级的东西。