gpt4 book ai didi

flutter - 为什么 "base is derivedA || base is derivedB"没有按预期工作?

转载 作者:行者123 更新时间:2023-12-02 10:56:10 26 4
gpt4 key购买 nike

if (state is NoteInitial || state is NewNote)
return ListView.builder(
itemCount: state.notes.length,
padding: EdgeInsets.symmetric(vertical: 10),
itemBuilder: (BuildContext context, int index) {
return _NoteCard(state.notes[index], key: UniqueKey(),);
});
NoteInitial 和 NewNote 都是从抽象类 NoteState 派生的,state 是一个 NoteState。如果我只写 if(state is NoteInitial)然后代码可以编译,如果我用 new NewNote 编写它,但如果我同时编写,编译器会提示 The getter 'notes' isn't defined for the type 'NoteState'. notes 在他们两个中都定义了,这是编译器的问题,还是我做错了什么?

最佳答案

编译器只能确保属性 notes如果它将变量的类型缩小到具有这些属性的特定类型,则存在。
我猜你的两种类型都有这个属性但彼此独立?但是编译器不能真正知道这一点。它没有将其缩小到特定类型。
如果是这样,那么您可能想要创建另一个基类或接口(interface),为它们实现它,然后使您的if声明取决于此。或者,也许您的一个州是另一个州的超集,这也可以。
我所做的是我有一个名为 NoteWithNotesState 的抽象状态。具有属性 notes然后是NewNoteInitialNote从中得出。那你if可能是 if(state is NoteWithNotesState)然后您应该能够毫无问题地访问该属性。

关于flutter - 为什么 "base is derivedA || base is derivedB"没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63485307/

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