Reputation:
I need to retrieve the value of index from .map()
class ImageSliderScreen extends StatefulWidget {
final List<RecipeStepsModel>? recipeStepsList;
ImageSliderScreen({required this.recipeStepsList});
@override
_ImageSliderScreenState createState() => _ImageSliderScreenState();
}
I have a list of RecipeStepsModel
and I need to build a image carousel out of it:
Container(
child: CarouselSlider(
options: CarouselOptions(height: 400.0),
items: widget.recipeStepsList!.map(
(i) {
return Builder(
builder: (BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(horizontal: 5.0),
child: ImageCarouselCard(
recipeSteps: widget.recipeStepsList![i], //error
),
);
},
);
},
).toList(),
),
),
I'm getting this error: The argument type 'RecipeStepsModel' can't be assigned to the parameter type 'int'
What am I missing here? how can I get the index of my recipeStepsList
?
Upvotes: 1
Views: 10677
Reputation: 974
Use list.asMap().entries.map((e) {})
.
e.key
will give the index
e.vaule
will give the value at that index
list.asMap().entries.map((e) {
// e.key will give you the index
print(e.key.toString());
// e.value will give you the value at that index
print(e.value.toString());
});
Upvotes: 7
Reputation: 5423
Have a look at the documentation of map
method. Your understanding of the method is wrong. The i
that you are wrongly assuming to be the index is not the index, but the item itself from the list. So you need to change to this.
Container(
child: CarouselSlider(
options: CarouselOptions(height: 400.0),
items: widget.recipeStepsList!.map(
(item) {
return Builder(
builder: (BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(horizontal: 5.0),
child: ImageCarouselCard(
recipeSteps: item,
),
);
},
);
},
).toList(),
),
),
Upvotes: 1