What's the best way to set up a ternary expression for an optional list stream (Stream<List<SubFoo>>?
)?
If there are items in the list, I want to display them in a StreamBuilder
, but if the list is empty, or the stream property is null, I want to return a different view.
It's optional because my app works as follows:
Foo
, if so, subscribe to the stream of SubFoo
for that Foo
Foo
, wait until the user manually creates one, then subscribe to the stream of SubFoo
My widget tree should return one of three views, depending on the data there:
Has Foo? | Has subFoo? | Widget to be returned |
---|---|---|
No | No | NoFooView() |
Yes | Yes, but the stream is empty | NoSubFooView() |
Yes | Yes, with active elements | StreamBuilderView() |
Here's how I currently have it set, but even when there are items in my subFooStream
(the third case in the table), the app still shows NoSubFooView()
:
return viewModel.foo == null ? NoFooView() : viewModel.subFooStream?.isEmpty != true ? NoSubFooView() : StreamBuilder(...);
I didn't do it as a ternary expression. I wrapped the second if/else condition within my stream builder. If there is a snapshot with data, and the length is greater than 0, it will return the StreamBuilderView()
, and if not, it will return the NoSubFooView()
.
viewmodel.Foo == null ? NoFooView() :
StreamBuilder<List<SubFooViewModel>>(
stream: subFooStream,
builder: ((context, snapshot) {
if (snapshot.data == null ||
snapshot.hasData == false ||
snapshot.data?.length == 0) {
return NoSubFooView(vm: vm);
} else {
return StreamBuilderView(...);
}
}),
),