Is there a way to add function to a list as list element without executing the function when the list is called in flutter?

Is there a way to add function to a list as list element without executing the function when the list is called in flutter?

I have a list of mapped articles with different functions. All I want to do is to add the various functions to the corresponding maps in the list. So that when any of the article is clicked the function attached will be executed

List articles = [
{
'index':0,
'name':'Education',
'function':function0(arg1,arg2)
},
{
'index':0,
'name':'Education',
'function':function1(arg1,arg2)
},
{
'index':0,
'name':'Education',
'function':function1(arg1,arg2)
}

]

Widget slider(){
 return CarouselSlider(
 items: articles.map((oneObject)=>Container(
   child: InkWell(
    onTap:()=>oneObject['function'],
    child: Text(oneObject['name'])
   )
  )
 );
);
}

What I want is when the list is displayed, then I can click each of the article to call the corresponding function, but, the functions are called immediately the app is opened

Answer

The issue you're experiencing is that your functions are being called immediately when the list is created because you're invoking them (function0(arg1,arg2)) rather than storing references to them. Here's how to fix this:

store the reference of the function like this

List articles = [
{
'index':0,
'name':'Education',
'function':(arg1, arg2) => function0(arg1, arg2),
},
// other items
];

then call the function like this:

 articles.map(
    (oneObject) => Container(
      child: InkWell(
        onTap: () => oneObject['function']("arg 1", "arge 2"),
        child: Text(oneObject['name']),
      ),
    ),
  );

for type safety you can also create a check before calling the function

// Define Type Aliases
typedef ArticleFunction = void Function(String arg1, String arg2);

articles.map(
    (oneObject) => Container(
      child: InkWell(
        onTap: () {
          final function = oneObject['function'];
          if (function case ArticleFunction fn) {
            fn("arg 1", "arge 2");
          }
        },
        child: Text(oneObject['name']),
      ),
    ),
  );

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles