我想在数据到达服务器时动态更改小部件颜色,但我不明白



我不明白如何根据socket.io的实时数据不断动态改变小部件的颜色。我想改变小部件的颜色时,数据将来自数据库。

Widget build(BuildContext context) {
return FutureBuilder<Room>(
future: roomService.getRoom(),
builder: (context, snapshot){
if(snapshot.hasData){
return GridView.builder(
itemCount: snapshot.data!.data.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
itemBuilder: (context, index){
var values = snapshot.data!.data[index];
return GestureDetector(
onTap: (){
Navigator.push(context, CupertinoModalPopupRoute(builder: (context)=>RoomDetailScreen(20, 30, 20+30)));
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.r),
),
color: Colors.green, //have to change here
elevation: 6,
child: Container(
alignment: Alignment.center,
child:Text(
"${values['RType']}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.sp,
color: AppColors.whiteSec),
),
),
),
);
},
);
}else if(snapshot.hasError){
return Center(
child: Column(
children: const [
Center(child: Icon(Icons.error,color: AppColors.yellowPri,)),
],
),
);
}
return const Center(child: CircularProgressIndicator());
}
);

}

如果你只需要根据数据在两种颜色之间切换

child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.r),
),
color: snapshot.data == 'Room-1' ? Colors.green : Colors.blue,
elevation: 6,

假设您的数据值之一是'Room-1'。

如果你要在多种颜色之间切换…

builder: (context, snapshot){
Map<String, Colour> colours = {
'Room-1': Colours.green,
'Room-2': Colours.blue,
'Room-3': Colours.red,
builder: (context, snapshot){
if(snapshot.hasData){
return GridView.builder(
itemCount: snapshot.data!.data.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
itemBuilder: (context, index){
var values = snapshot.data!.data[index];
return GestureDetector(
onTap: (){
Navigator.push(context, CupertinoModalPopupRoute(builder: (context)=>RoomDetailScreen(20, 30, 20+30)));
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.r),
),
color: Colors.green, //have to change here
elevation: 6,
child: Container(
};
if(snapshot.hasData){
return GridView.builder(
itemCount: snapshot.data!.data.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
itemBuilder: (context, index){
var values = snapshot.data!.data[index];
return GestureDetector(
onTap: (){
Navigator.push(context, CupertinoModalPopupRoute(builder: (context)=>RoomDetailScreen(20, 30, 20+30)));
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.r),
),
color: colours[snapshot.data],
elevation: 6,
child: Container(

注意:你的问题说你想改变颜色'当数据将来自数据库'。但是由于您已经使用了snapshot.hasData,如果没有来自DB的任何数据,GridView本身将不会呈现。

相关内容

  • 没有找到相关文章

最新更新