I have an app where a collection has a field ‘Status’. This field changes with the use of streamBuilder. works well. I can access the updated changes.
However, I want to change the TextStyle of that particular field depending the the data in the fied ‘Status’.
The data in the ‘Status’ field are : ‘not verified’, ‘pending verification’, ‘verified’.
I want the textstyle(say the color) to change depending on the ‘Status of the user
I have no idea how to do it. Any help.
Here is the code:
final uid = FirebaseAuth.instance.currentUser!.uid;
CollectionReference users = FirebaseFirestore.instance.collection('users');
StreamBuilder(
stream: users.doc(uid).snapshots(),
builder: (BuildContext context,
AsyncSnapshot snapshot) {
String status = snapshot.data['Status'];
if (snapshot.connectionState ==
ConnectionState) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Text(status);
}),
],
>Solution :
To change the TextStyle based on the value of the ‘Status’ field, you can use a conditional statement to determine the appropriate TextStyle to apply. Here’s an example of how you can modify your code to achieve this:
final uid = FirebaseAuth.instance.currentUser!.uid;
CollectionReference users = FirebaseFirestore.instance.collection('users');
StreamBuilder(
stream: users.doc(uid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
String status = snapshot.data['Status'];
TextStyle textStyle;
if (status == 'not verified') {
textStyle = TextStyle(color: Colors.red);
} else if (status == 'pending verification') {
textStyle = TextStyle(color: Colors.yellow);
} else if (status == 'verified') {
textStyle = TextStyle(color: Colors.green);
} else {
textStyle = TextStyle(color: Colors.black);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Text(
status,
style: textStyle,
);
},
),
In this example, we use a conditional statement to check the value of the ‘Status’ field and assign the appropriate TextStyle to the ‘textStyle’ variable. We then pass this variable to the ‘style’ parameter of the Text widget. Note that we also check the connection state of the snapshot to ensure that we show a loading indicator while the data is being fetched.