gpt4 book ai didi

flutter - 使用提供程序和 snackbar 查找停用的小部件的祖先是不安全的

转载 作者:行者123 更新时间:2023-12-03 03:51:27 25 4
gpt4 key购买 nike

我正在使用DismissibleWidget从列表中删除注释。删除便笺后,会调用Snackbar,以使用户有机会撤消操作。单击该按钮,然后将该便笺重新插入列表中时,将出现以下错误:
处理手势时引发了以下断言:
查找停用的窗口小部件的祖先是不安全的。
此时,小部件的元素树的状态不再稳定。

  • 可禁用的小部件
                 Dismissible(
    direction: DismissDirection.endToStart,
    onDismissed: (direction){
    var removedNote = list.notes[index];
    Provider.of<ListProvider>(context, listen: false).removeNote(index);

    Scaffold.of(context).showSnackBar(
    SnackBar(
    content: Text("Nota removida"),
    action: SnackBarAction(
    label: "Desfazer",
    onPressed: (){
    Provider.of<ListProvider>(context, listen: false).insertNote(removedNote, index);
    },
    ),
    duration: Duration(seconds: 3),
    ),
    );
    },
    ...
  • 提供者中的方法
    void insertNote(NoteModel note, int index){
    notes.insert(index, note);
    fileRepository.saveToFile(notes);
    notifyListeners();
    }
  • 最佳答案

    我遇到了一些问题,但是使用BLoC作为状态管理,我的解决方案是从该小部件上方获取上下文。
    什么地方出了错?
    您试图寻找一个不再可用的上下文。由于variable shadowing也会发生这种情况。
    解?
    到达该小部件上方的内容。
    伪 flutter 码

    class NameOfYourClass{
    build(BuildContext context1) {
    return ListView.builder(
    itemBuilder: (context2, index) {
    return MyItem();
    }
    );
    }
    }
    假设您使用 MyItem小部件关闭了 Dismissible,则 context2将不再可用,如果您打印 context2,它将看起来像这样( 注意:当 MyItem被关闭时):
    SliverList(delegate: SliverChildBuilderDelegate#66afb(estimated child count: 1), renderObject: RenderSliverList#593ed relayoutBoundary=up2 DETACHED)
    如您所见,该项目是树中的 DETACHED。如果您打印context1,它将看起来像这样。
    NameOfYourClass
    因此,总而言之,不要这样做:
     Provider.of<ListProvider>(context2, listen: false).insertNote(removedNote, index);
    做这个:
     Provider.of<ListProvider>(context1, listen: false).insertNote(removedNote, index);
    不要使用context1或context2,这只是出于说明目的。

    关于flutter - 使用提供程序和 snackbar 查找停用的小部件的祖先是不安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63144418/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com