[英]StreamBuilder with flutter_firebase has null value on second widget build (image disappears)
I managed to show images from firestore using streambuilder
on a page, but the problem is that the image disappears (I get a null snapshot.data
value) if I go back to the last page and come back.我设法在页面上使用
streambuilder
显示来自 firestore 的图像,但问题是如果我 go 回到最后一页并返回,图像会消失(我得到 null snapshot.data
值)。
Here is my code.这是我的代码。 How can I make the snapshot data persist, so the image stays there and doesn't disappear when the widget rebuilds?
如何使快照数据持久存在,以便图像保持在那里并且在小部件重建时不会消失?
Container(child: Column(
children: [
Text(' Certifications',
Container(child: StreamBuilder(
stream: certificates,
builder: (context, snapshot) {
return !snapshot.hasData
? Center(child: Container(
child: Center(child: Text(
'No images yet'))))
: Container(
child: GridView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
url = snapshot.data.documents[index].get('url');
return Container(child: FadeInImage
.memoryNetwork(fit: BoxFit.cover,
placeholder: kTransparentImage,
image: url),
),
);
}),
);
}),
),
Streams are asynchronous.流是异步的。 which means
StreamBuilder
does not get old snapshots, only new future snapshots.这意味着
StreamBuilder
不会获取旧快照,只会获取新的未来快照。 This is your problem.这是你的问题。
When your widget is re-built it is subscribing to a stream that has already had events.当您的小部件重新构建时,它正在订阅一个已经有事件的 stream。 Yes you would think that data in the snapshot should be the last event value, but that is not the case.
是的,您会认为快照中的数据应该是最后一个事件值,但事实并非如此。 It will be
null
until a new event is pushed onto your certificates
stream.在将新事件推送到您的
certificates
null
之前,它将是 null。
So one solution is for the service that is loading your certificates to store the value of the initial API request and make that available for you to use in your StreamBuilder's initialData
property.因此,一种解决方案是让正在加载证书的服务存储初始 API 请求的值,并使其可用于 StreamBuilder 的
initialData
属性。
I would structure it like this:我会这样构造它:
StreamBuilder(
stream: certificateService.stream,
initialData: certificateService.value, // <-----
builder: ...
)
Hope this points you in the right direction.希望这能为您指明正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.