在尝试使用Dismissible ListView删除futurebuilder内的项目时,颤振获得范围错误



我想要一个来自firestore的项目列表,我想要显示这些项目,并且用户可以取消它们。(我这样做的FirebaseApi().getSwiperData(fooNotifier)是给我一个我想要的数据的副本)如果列表是空的,我想显示一个消息。

当我试图实现它没有setstate我得到以下范围错误:

════════ Exception caught by widgets library ═══════════════════════════════════
The following RangeError was thrown building:
RangeError (index): Invalid value: Not in inclusive range 0..2: 3

在我看来,没有必要setstate,因为我与Consumer工作,但有些东西不工作在这里,我真的没有一个想法了。

使用setstate一切工作正常,但我不希望整个小部件重建。

我代码:

class _SwipeScreenState extends State<SwipeScreen> {
Future fooFuture;
@override
void initState() {
// TODO: implement initState
super.initState();
final fooNotifier = Provider.of<FooNotifier>(context, listen: false);
fooFuture = FirebaseApi().getSwiperData(fooNotifier);
}
@override
Widget build(BuildContext context) {
print('rebuild swipescreen');
return Stack(
children: [
Consumer<FooNotifier>(builder: (__, consumerValues, _) {
return FutureBuilder(
future: fooFuture,
// ignore: missing_return
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
break;
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
break;
case ConnectionState.done:
return consumerValues.swiperList.length != 0
? ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: consumerValues.swiperList.length ?? 0,
itemBuilder: (BuildContext context, int index) {
return Dismissible(
resizeDuration: Duration(milliseconds: 1500),
onDismissed: (DismissDirection direction) {
//setState(() {
//Doesnt work here like expected
consumerValues.swiperList.removeAt(index);
print(consumerValues.swiperList);
// });
},
secondaryBackground: Container(
child: Center(
child: Text(
'geliked',
style: TextStyle(color: Colors.black),
),
),
color: Colors.lightGreenAccent,
),
background: Container(
child: Center(
child: Text(
'Nicht interessant',
style: TextStyle(color: Colors.black),
),
),
color: Colors.redAccent),
child: SwipeCard(
cardWidth: MediaQuery.of(context).size.width * 1,
cardHeight:
MediaQuery.of(context).size.height * 1,
foo2Name:
consumerValues.swiperList[index].foo2Name,
fooName:
consumerValues.swiperList[index].fooName,
imageUrl:
consumerValues.swiperList[index].imageUrl,
),
key: UniqueKey(),
direction: DismissDirection.horizontal,
);
},
)
: SwipeNoItems(); // Showing up if the list is empty
break;
default:
}
},
);
}),
],
);

我很自豪地告诉你,我解决了这个问题。我还是个新手,我可以想象这对新手来说也是一个常见的错误。

正如你在我的代码中看到的,我正在使用FutureBuilder,这基本上只是一个具有异步操作和状态管理的ListView.Builder

所以当我收到数据时,我把它们展示给用户。因为我正在使用来自提供商包的Consumers,它侦听任何状态更改(这也是为什么我不需要SetState在这里),我接收任何类型的更改。

现在,而不是删除我的索引与consumerValues.swiperList.removeAt(index);,这不能传达我的变化

我在我的通知类中创建了一个函数:

void removeSwipeItems(idx){
_swiperList.removeAt(idx);
notifyListeners();
}

并调用函数which does communicate my changes

consumerValues.removeSwipeItems(index);

最新更新