5

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

1 Answer 1

11

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);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to pass it explicitly as an argument though ?
No and it wouldn't make sense. If you'd provide more context why you need this it would be easier to to make suggestions. I'll add one to my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.