Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass extra arguments to itemBuilder function of ListView.builder Widget in Flutter?

I want to pass extra arguments to my itemBuilder function apart from content and index . How do I do this ?

body: new ListView.builder
  (
    itemCount: litems.length,
    itemBuilder: (BuildContext ctxt, int index) {
     return new Text(litems[index]);
    }
  )

I want something that does this :

int k = "HI";
body: new ListView.builder
  (
    itemCount: litems.length,
    itemBuilder: (BuildContext ctxt, int index, String k) {
     return new Text(litems[index] + k);
    }
  )
like image 941
Keshav Aditya R.P Avatar asked Jan 02 '23 20:01

Keshav Aditya R.P


1 Answers

There is no need for that.

You can access k from within the builder function body just fine without passing it as parameter.
You pass an inline function and that has access to the scope where it is defined.

If you don't have an inline builder function and you want/need to pass additional arguments you can use

String k = "HI";    
child: new ListView.builder(
  itemCount: litems.length,
  itemBuilder: (ctxt, Index) => _listItemBuilder(ctxt, Index, k)
)

...

Widget _listItemBuilder(BuildContext ctxt, int Index, String k) {
    return new Text(litems[Index] + k);
  }
like image 130
Günter Zöchbauer Avatar answered Jan 10 '23 20:01

Günter Zöchbauer