也许我把结构弄错了,所以任何建议都将不胜感激。
这是我的课程:
class MainClass {
final String title;
MainClass({this.title});
}
class SubClass1 extends MainClass {
final String subClass1Info;
SubClass1({this.subClass1Info});
}
class SubClass2 extends MainClass {
final String subClass2Info;
SubClass2({this.subClass2Info});
}
class SubClass3 extends MainClass {
final String subClass3Info;
SubClass3({this.subClass3Info});
}
然后我有一个StreamBuilder:
StreamBuilder<MainClass>(
stream: _bloc.stream,
builder: (BuildContext context, AsyncSnapshot<MainClass> snapshot) {
});
SubClass1,SubClass2或SubClass3都可以通过流发送,子Widget将需要知道它们正在处理的类型。
我如何最好地实现这一目标?
答案 0 :(得分:2)
您可以使用is
关键字检查对象是否是您的Classes
StreamBuilder<MainClass>(
stream: null,
builder: (BuildContext context, AsyncSnapshot<MainClass> snapshot) {
if (snapshot.hasData) {
if (snapshot.data is SubClass1) {
final SubClass1 myData = snapshot.data as SubClass1;
return Container(
child: Text("SubClass1"),
);
} else if (snapshot.data is SubClass2) {
final SubClass2 myData = snapshot.data as SubClass2;
return Container(
child: Text("SubClass2"),
);
} else if (snapshot.data is SubClass3) {
final SubClass3 myData = snapshot.data as SubClass3;
return Container(
child: Text("SubClass3"),
);
}
} else {
return Center(
child: CircularProgressIndicator(),
);
}
})