Home > Enterprise >  Pass variable to child widget FLUTTER
Pass variable to child widget FLUTTER

Time:03-22

I've got Container with ListView Builder with child widget placed in separated file.

itemCount: articles.length,
itemBuilder: (context, index ) => allRadioList(articles[index], context),
            

My child widget:

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: () {},
    ),
  ));

How can i pass IE STRING VARIABLE in child allRadioList widget from parent?

CodePudding user response:

  1. Add a new parameter to your builder function:
Widget allRadioList(
  Article article, 
  BuildContext context,
  String text, // <-- New variable
) {
  return <...>;
}
  1. Pass the variable to the builder:
final text = 'Test';

<...>

itemCount: articles.length,
itemBuilder: (context, index ) => allRadioList(
  articles[index],
  context,
  text, // <-- Pass variable
),
  1. Use the passed value in the code:
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: () {},
    ),
  ));
  • Related