"RangeError (index): Invalid value: Valid value range is empty: 2" 带有 flutter 轮播
"RangeError (index): Invalid value: Valid value range is empty: 2" with flutter carousel
imageList 列表包含从 JSON 文件中提取的图像路径。但是,这个问题只遇到过一次,热重载后就消失了。
使用的包:carousel_slider:^3.0.0
代码:
CarouselSlider(
options: CarouselOptions(
height: 250.0,
enlargeCenterPage: true,
autoPlay: true,
reverse: false,
enableInfiniteScroll: true,
autoPlayInterval: Duration(seconds: 3),
autoPlayAnimationDuration: Duration(milliseconds: 2000),
pauseAutoPlayOnTouch: true,
scrollDirection: Axis.horizontal,
),
items: imageList.map((img) {
return Builder(
builder: (BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 10.0
),
decoration: BoxDecoration(
color: Colors.transparent,
),
child: Image.asset(
img,
fit: BoxFit.fill,
),
);
},
);
}).toList(),
),
我猜你的 imageList 一开始是空的,当你填充它时你没有调用 setstate() 如果你调用了这意味着轮播不允许你使用空列表
添加一个 if 语句,这样如果列表为空就不会构建 carouselSlider
if(!imageList.isEmpty)
CarouselSlider()
imageList 列表包含从 JSON 文件中提取的图像路径。但是,这个问题只遇到过一次,热重载后就消失了。 使用的包:carousel_slider:^3.0.0
代码:
CarouselSlider(
options: CarouselOptions(
height: 250.0,
enlargeCenterPage: true,
autoPlay: true,
reverse: false,
enableInfiniteScroll: true,
autoPlayInterval: Duration(seconds: 3),
autoPlayAnimationDuration: Duration(milliseconds: 2000),
pauseAutoPlayOnTouch: true,
scrollDirection: Axis.horizontal,
),
items: imageList.map((img) {
return Builder(
builder: (BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 10.0
),
decoration: BoxDecoration(
color: Colors.transparent,
),
child: Image.asset(
img,
fit: BoxFit.fill,
),
);
},
);
}).toList(),
),
我猜你的 imageList 一开始是空的,当你填充它时你没有调用 setstate() 如果你调用了这意味着轮播不允许你使用空列表 添加一个 if 语句,这样如果列表为空就不会构建 carouselSlider
if(!imageList.isEmpty)
CarouselSlider()