Ad

Pass Variable To Child Widget FLUTTER

- 1 answer

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?

Ad

Answer

  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: () {},
    ),
  ));
Ad
source: stackoverflow.com
Ad