flutterfirebasegoogle-cloud-firestorefirebase-authenticationtextstyle

flutter firebase: Change property with corresponding data


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

  • Create a Map with the statuses and the colors assigned to each of them:

    const statusColors = <String, Color> {
      'not verified': Colors.red,
      'pending verification': Colors.orange,
      'verified': Colors.green,
    };
    

    In the StreamBuilder assign a TextStyle with color based on this map; you can use the style parameter of the Text widget:

    return Text(status, style: TextStyle(color: statusColors[status]));