Search code examples
fluttersqflite

i want rawquery to be nullable


static Future<int> getWaterDrank() {
final db = await WaterDBHelper.db()'
List result = await db.rawQuery(
"SELECT * FROM $tablename WHERE $columnDate = ?", [dateCurrent]
);
var waterDrank = result[0]['waterDrank'];
return int.parse(waterDrank);
}

This function in my db will be in charge of retrieving all the data with today's date, which will always be 1.

The problem is that the logic doesn't work when the data first retrieves nothing due to what is stored being null.

I use this command to see if it is truly null, then insert - however it does not let me check if it is null and prints the error

null check operator used on a null value

This is the logic

  • check any data available with today's date
  • initially is nothing
  • this function should return nothing <------ error occurs here
  • if empty then insert with insert function

the function is called from a stateless widget - it is in charge of structuring the buttons and there onPressed function. this function will then go into the on-Pressed function later

    getWaterDrankStored (WaterButtonModel) async {
      int waterStoredValueConvert = await WaterDBHelper.getWaterDrank();                // int stored in db
      waterStoredValueInteger = waterStoredValueConvert;                                // pass it on to this variable
      print('4      this is the instance of getWaterStore ${waterStoredValueInteger}');

      int WaterDrank = WaterButtonModel.waterMillimeters;                               // value of button pressed
      TotalWaterDrank = waterStoredValueInteger + WaterDrank;                           // value of button + stored
      print('5      total water  ${TotalWaterDrank} ml');

      // save value to preferences
      Provider.of<WaterProvider>(context,listen: false).loadWaterData(waterStoredValueConvert); // this saved value in provider
      // stored plus pressed rn


      if (filteredInputs.isEmpty) {//insert
        print('7     insert command ran - ${TotalWaterDrank}');
        return _addWater();
      }
      else {     //update milliliters
        print('8     update command ran - ${TotalWaterDrank}');
        return _updateWaterThrouDate(dateNow, waterStoredValueConvert);
      }
    }

the idea is that each button has a value, when i press the button the function will add the value (may be) previously stored in db and the value of the button.

this it messages i get - it indicats the function in db is not fully executed not sure why

I/flutter ( 8512): 1      the size of button pressed: 250 ml
I/flutter ( 8512): []
I/flutter ( 8512): 2      value of filtered inputs after []
I/flutter ( 8512): 3      number of items should always be 1: 0
D/EGL_emulation( 8512): app_time_stats: avg=27.14ms min=4.32ms max=214.38ms count=29
I/flutter ( 8512): this is the result []
E/flutter ( 8512): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 8512): #0      QueryResultSet.[] (package:sqflite_common/src/collection_utils.dart:107:32)
E/flutter ( 8512): #1      WaterDBHelper.getWaterDrank (package:progressiverecording/services/sqflite/sqflite_water/water_db_helper.dart:127:30)

note that after "3 ------" is printed it should then run the function in db, maybe it has to do something about how the db is initiated is what i was hinted at.

this is another function that is responsible to filter data not important but helps with the picture

    getUserInputDate() async {
      filteredInputs = await WaterDBHelper.getWaterDateFilter();
      print('2      value of filtered inputs after $filteredInputs');
      print('3      number of items should always be 1: ${ filteredInputs.length}');


    }

this the onpressed method.

    addInput(WaterButtonModel)  async {
      print('1      the size of button pressed: ${WaterButtonModel.waterMillimeters} ml');
// this order check -> getUser -> getWater
      await getUserInputDate();
      await getWaterDrankStored(WaterButtonModel);
       print('============================');

       Provider.of<WaterProvider>(context,listen: false).changeWaterValue(TotalWaterDrank);
    }

if you noticed i have added numbers to see what is being executed, the problem solely seems to be in the getWaterDrankStored.


Solution

  • First make function return type nullable and follow the code below

    static Future<int?> getWaterDrank() async {
        final db = await WaterDBHelper.db();
        List result = await db.rawQuery(
            "SELECT * FROM $tablename WHERE $columnDate = ?", [dateCurrent]
        );
        if (result.isEmpty()) {
          return null;
        }else {
          var waterDrank = result[0]['waterDrank'];
          return int.parse(waterDrank);
        }
      }
    

    On UI layer you can check the data is null or not by using this db function