我有一个Websocket应用程序,该应用程序使用StreamBuilder
来构建GridView
,数据每1秒流一次。现在,每隔1秒钟就会重新构建整个GridView
,我认为这不是最佳的处理方式,因为我只想更新GridView
中元素的内容。对于类似的情况,您会采取什么方法?
这是StreamBuilder
Widget buildDataStream() {
return StreamBuilder(
stream: widget.channel.stream,
builder: (context, snapshot) {
return Container(
child: snapshot.hasData ? buildRoomTiles(snapshot.data) : Container(),
);
},
);
}
这里是嵌套的组件
Widget buildRoomTiles(jsonString) {
var nodeCount = 0;
Map<String, Object> node = jsonDecode(jsonString);
List<SensorNode> nodeList = [];
node.forEach((key, value) {
nodeCount++;
var sensorNode = SensorNode.fromJson(node[key]);
nodeList.add(sensorNode);
});
return GridView.count(
crossAxisCount: 2,
children: List.generate(
nodeCount,
(index) => buildSingleRoomCard(nodeList[index]),
),
);
}
Widget buildSingleRoomCard(SensorNode node) {
var smartSize = (MediaQuery.of(context).size.width - 40) / 2;
return Padding(
padding: const EdgeInsets.only(top: 15.0),
child: Stack(
alignment: Alignment.center,
children: [
Container(
width: smartSize,
height: smartSize,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.25),
blurRadius: 7,
offset: Offset(0, 4),
)
],
borderRadius: BorderRadius.all(Radius.circular(10.0)),
image: DecorationImage(
image: AssetImage('assets/images/livingroom.jpg'),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(colorCommondorBlue.withOpacity(0.1), BlendMode.srcOver),
),
),
),
],
),
);
}
谢谢