【发布时间】:2021-05-30 23:40:36
【问题描述】:
我想要一个来自我的 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:
}
},
);
}),
],
);
【问题讨论】:
标签: firebase flutter flutter-provider flutter-futurebuilder