Keshav Aditya R P
Keshav Aditya R P

Reputation: 3221

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);
    }
  )

Upvotes: 5

Views: 3890

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657148

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);
  }

Upvotes: 11

Related Questions