将变量传递给子部件 FLUTTER
Pass variable to child widget FLUTTER
我有带有 ListView Builder 的容器,子小部件放在单独的文件中。
itemCount: articles.length,
itemBuilder: (context, index ) => allRadioList(articles[index], context),
我的子插件:
Widget allRadioList(Article article, BuildContext context) {
return Card(
child: ListTile(
title: Text(article.title),
subtitle: Text(STRING VARIABLE),
leading: CircleAvatar(backgroundImage: NetworkImage("https://image.tmdb.org/t/p/w300/${article.urlToImage}")),
trailing: IconButton(
icon: const Icon(Icons.star_border_outlined),
tooltip: 'Increase volume by 10',
onPressed: () {},
),
));
我如何在父级的子 allRadioList 小部件中传递 IE STRING VARIABLE?
- 向您的
builder
函数添加一个新参数:
Widget allRadioList(
Article article,
BuildContext context,
String text, // <-- New variable
) {
return <...>;
}
- 将变量传递给构建器:
final text = 'Test';
<...>
itemCount: articles.length,
itemBuilder: (context, index ) => allRadioList(
articles[index],
context,
text, // <-- Pass variable
),
- 在代码中使用传递的值:
Widget allRadioList(
Article article,
BuildContext context,
String text,
) {
return Card(
child: ListTile(
title: Text(article.title),
subtitle: Text(text), // <-- Use the passed value
leading: CircleAvatar(backgroundImage: NetworkImage("https://image.tmdb.org/t/p/w300/${article.urlToImage}")),
trailing: IconButton(
icon: const Icon(Icons.star_border_outlined),
tooltip: 'Increase volume by 10',
onPressed: () {},
),
));
我有带有 ListView Builder 的容器,子小部件放在单独的文件中。
itemCount: articles.length,
itemBuilder: (context, index ) => allRadioList(articles[index], context),
我的子插件:
Widget allRadioList(Article article, BuildContext context) {
return Card(
child: ListTile(
title: Text(article.title),
subtitle: Text(STRING VARIABLE),
leading: CircleAvatar(backgroundImage: NetworkImage("https://image.tmdb.org/t/p/w300/${article.urlToImage}")),
trailing: IconButton(
icon: const Icon(Icons.star_border_outlined),
tooltip: 'Increase volume by 10',
onPressed: () {},
),
));
我如何在父级的子 allRadioList 小部件中传递 IE STRING VARIABLE?
- 向您的
builder
函数添加一个新参数:
Widget allRadioList(
Article article,
BuildContext context,
String text, // <-- New variable
) {
return <...>;
}
- 将变量传递给构建器:
final text = 'Test';
<...>
itemCount: articles.length,
itemBuilder: (context, index ) => allRadioList(
articles[index],
context,
text, // <-- Pass variable
),
- 在代码中使用传递的值:
Widget allRadioList(
Article article,
BuildContext context,
String text,
) {
return Card(
child: ListTile(
title: Text(article.title),
subtitle: Text(text), // <-- Use the passed value
leading: CircleAvatar(backgroundImage: NetworkImage("https://image.tmdb.org/t/p/w300/${article.urlToImage}")),
trailing: IconButton(
icon: const Icon(Icons.star_border_outlined),
tooltip: 'Increase volume by 10',
onPressed: () {},
),
));