Home > Mobile >  Add a ternary or if operator to detect a condition in outputted text in a Flutter StreamBuilder?
Add a ternary or if operator to detect a condition in outputted text in a Flutter StreamBuilder?

Time:02-23

The code below is a StreamBuilder that prints several fields from a stream. Is it possible to add a ternary or if operator to the Text widget that checks if the result is above zero, and if so, add a prefix to the output? Would it also be possible to change the color of the text to green if it is above zero and red if it is below?

                                  Text(
                                          data['pointsfrom'].toString(),
                                          style: GoogleFonts.poppins(
                                            color: Colors.white70,
                                            fontSize: 27,
                                          ),
                                        ),

Full Code

import 'package:appforpoints/dashboardPages/adminPage/listCards/admin_notif_card.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';

class PointsHistory extends StatefulWidget {
  final String username;
  const PointsHistory({Key? key, required this.username}) : super(key: key);

  @override
  _PointsHistoryState createState() => _PointsHistoryState();
}

class _PointsHistoryState extends State<PointsHistory> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xff2F3439),
      body: SizedBox(
        height: double.infinity,
        child: Padding(
          padding: const EdgeInsets.only(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                child: ListView(
                  scrollDirection: Axis.vertical,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(
                        top: 80,
                        left: 23,
                      ),
                      child: StreamBuilder<QuerySnapshot>(
                        stream: FirebaseFirestore.instance
                            .collection("pointslogs")
                            .where("uid",
                                isEqualTo:
                                    FirebaseAuth.instance.currentUser!.uid)
                            .where('username', isEqualTo: widget.username)
                            .orderBy('timestamp', descending: true)
                            .snapshots(),
                        builder: (BuildContext context,
                            AsyncSnapshot<QuerySnapshot> snapshot) {
                          if (snapshot.hasError) {
                            return const Text('Something went wrong');
                          }

                          if (snapshot.connectionState ==
                              ConnectionState.waiting) {
                            return const Text("Loading");
                          }
                          return Column(
                            children: snapshot.data!.docs.map(
                              (DocumentSnapshot document) {
                                Map<String, dynamic> data =
                                    document.data()! as Map<String, dynamic>;
                                return Column(
                                  children: [
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Text(
                                          data['pointsfrom'].toString(),
                                          style: GoogleFonts.poppins(
                                            color: Colors.white70,
                                            fontSize: 27,
                                          ),
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.only(
                                              left: 12, right: 12),
                                          child: Text(
                                            '>',
                                            style: GoogleFonts.poppins(
                                              color: Colors.white70,
                                              fontSize: 27,
                                            ),
                                          ),
                                        ),
                                        Text(
                                          data['pointsto'].toString(),
                                          style: GoogleFonts.poppins(
                                            color: Colors.white70,
                                            fontSize: 27,
                                          ),
                                        ),
                                        Padding(
                                          padding:
                                              const EdgeInsets.only(left: 20),
                                          child: Text(
                                            data['pointschange'].toString()  
                                                " ",
                                            style: GoogleFonts.poppins(
                                              color: Colors.white70,
                                              fontSize: 27,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    Row(
                                      children: [
                                        Text(
                                          data['date'].toString(),
                                        ),
                                        Text(
                                          data['time'].toString(),
                                        ),
                                      ],
                                    )
                                  ],
                                );
                              },
                            ).toList(),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );

    /*Scaffold(
      backgroundColor: const Color(0xff1e272c),
      body: ListView(
        scrollDirection: Axis.horizontal,
        children: [
          StreamBuilder<QuerySnapshot>(
            stream: userLog,
            builder:
                (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (snapshot.hasError) {
                return const Text('Something went wrong');
              }

              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Text("Loading");
              }
              return Row(
                children: snapshot.data!.docs.map(
                  (DocumentSnapshot document) {
                    Map<String, dynamic> data =
                        document.data()! as Map<String, dynamic>;
                    return Column(
                      children: [
                        Text(data['pointschange']),
                        Text(data['pointsto']),
                      ],
                    );
                  },
                ).toList(),
              );
            },
          ),
        ],
      ),
    );*/
  }
}

CodePudding user response:

You mean like this:

Text(
  (data['pointsfrom'] >= 0 ? ' ' : '')   data['pointsfrom'].toString(),
  style: GoogleFonts.poppins(
    color: data['pointsfrom'] >= 0 ? Colors.green : Colors.red,
    fontSize: 27,
  ),
),

Suggestion: I noticed you were repeating the style over and over (GoogleFonts.poppins); you could either set it once at the top of the build method or create a separate utility class where you can have all these values there. You could create styles per condition, which you could also extract as a separate method that generates the proper styles for you based on the desired condition.

Also you could move the prefixing logic to a separate method so the ternary operation doesn't look too messy.

  • Related