使用Unique Key时不更改可禁用的小部件



因此,我尝试使用一个可丢弃的小部件作为Flutter代码的一部分。它运行良好,除非我滑动到第一个文档之前或最后一个文档之后。下面是我使用过的代码示例:

StreamBuilder <QuerySnapshot>(
stream: _firestore.collection('articles').snapshots(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text("Error fetching posts ${snapshot.error}"),);
}
if (snapshot.hasData) {
List<DocumentSnapshot> documents = snapshot.data.documents;
return GestureDetector(
onHorizontalDragUpdate: (dragUpdateDetails) {
Navigator.push(context,
MaterialPageRoute(builder: (context) => WebViewContainer(documents[index].data['url'])));              },
child: Dismissible(
key: Key(index.toString()),
direction: DismissDirection.vertical,
onDismissed: (direction) {
setState(() {
documents.removeAt(index);
index = (index==documents.length -1) ? index = 0 : index++;
});
},

代码运行良好,直到我到达文档列表的末尾。我收到的错误消息如下:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building Dismissible-[<'0'>](dirty, state: _DismissibleState#6b64c(tickers: tracking 2 tickers)):
A dismissed Dismissible widget is still part of the tree.

Make sure to implement the onDismissed handler and to immediately remove the Dismissible widget from the application once that handler has fired.
The relevant error-causing widget was: 
Dismissible-[<'0'>] file:///C:/Users/Lenovo/AndroidStudioProjects/sevenlines/lib/widgets/newspage.dart:63:24
When the exception was thrown, this was the stack: 
#0      _DismissibleState.build.<anonymous closure> (package:flutter/src/widgets/dismissible.dart:526:11)
#1      _DismissibleState.build (package:flutter/src/widgets/dismissible.dart:535:8)
#2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4334:27)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
A dismissed Dismissible widget is still part of the tree.
The relevant error-causing widget was: 
Dismissible-[<'0'>] file:///C:/Users/Lenovo/AndroidStudioProjects/sevenlines/lib/widgets/newspage.dart:63:24
════════════════════════════════════════════════════════════════════════════════════════════════════

在检查了这个问题的解决方案后,我决定从依赖索引的键切换到UniqueKey。但现在它根本不会在列表中移动——页面停留在第一个文档本身。请告知。

尝试在key: Key(index.toString()),中使用ObjectKey而不是Key,并将对象数据作为参数。

最新更新