Flutter 从.map()获取索引值

lstz6jyr  于 2023-02-13  发布在  Flutter
关注(0)|答案(2)|浏览(855)

我需要从.map()中检索index的值

class ImageSliderScreen extends StatefulWidget {
  final List<RecipeStepsModel>? recipeStepsList;
  ImageSliderScreen({required this.recipeStepsList});
  @override
  _ImageSliderScreenState createState() => _ImageSliderScreenState();

}

我有一个RecipeStepsModel的列表,我需要从中构建一个图像轮播:

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(),
        ),
      ),

我得到这个错误:The argument type 'RecipeStepsModel' can't be assigned to the parameter type 'int'
这里我遗漏了什么?我怎样才能得到我的recipeStepsList的索引?

tquggr8v

tquggr8v1#

使用list.asMap().entries.map((e) {})
e.key将给出索引e.vaule将给出该索引处的值

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

sy5wg1nm2#

再看一下map方法的documentation,你对方法的理解是错误的,你误以为是索引的i并不是索引,而是列表中的项本身,所以你需要改成这样。

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(),
        ),
      ),

相关问题