0

所以我试图在我的 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。但现在它根本不会在列表中移动——页面停留在第一个文档本身。请指教。

4

1 回答 1

0

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

于 2020-04-12T17:30:57.563 回答