简体   繁体   中英

How to Change icon color according to variable value in flutter

I want to change the icon button color according to the variable value. eg: if the variable value is greater than 40 icon color should be red other wise icon color is white. I get a variable values from SQLite table. following code, i have tried but its shows null check operator used on null value.\

                      int? tatalLeave=0;                

                         IconButton(
                          onPressed: (() {
                            getTotalLeave();
                          }),
                          icon: Icon(
                            Icons.notifications_active_rounded,
                            color:
                                tatalLeave! >= 40 ? Colors.red : Colors.white,
                            size: 30.0,
                          ),
                        )

following i have added sqlite codes

//get total number of leaves
  getTotalLeave() async {
    int? count = await DatabaseHelper.instance.countAllLeave();
    setState(() {
      tatalLeave = count;
      print(tatalLeave);
    });
  }
}

db helper class

Future<int?> countAllLeave() async {
    Database db = await database;
    final allLeave = Sqflite.firstIntValue(
        await db.rawQuery('SELECT SUM(num_leave_days) FROM leave_Details'));
    return allLeave;
  }

please help me to slove my issue.

Try modifiying the code as below, As the getTotalLeave function is asynchronous you need to put await.

(await is to interrupt the process flow until the async method completes)

                      int? tatalLeave=0;                

                         IconButton(
                          onPressed: (()async {
                          await  getTotalLeave();
                          }),
                          icon: Icon(
                            Icons.notifications_active_rounded,
                            color:
                                tatalLeave! >= 40 ? Colors.red : 
                          Colors.white,
                            size: 30.0,
                          ),
                        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM