Check Empty Fluttter async return

Asked

Viewed 560 times

1

How can I check if a return async of a particular sqlite is empty?

I need to check if the "resultReceita" is null before displaying it in the widget.

I tried with an if however, I did not succeed. This code works perfectly, but when the user installs for the first time he has not made releases, thus returns a "null" error in futurebuilder.

My code:

    @override
  Widget build(BuildContext context) {
    //FUTURE BUILDER PARA EXIBIR SALDO CONTAS
    Future<int> _query() async {
      var db = await DatabaseHelper.instance.database;
      var resultReceita = await db.rawQuery('SELECT SUM(valor) FROM lancamentos WHERE tipo = "R"');
      var resultDespesa = await db.rawQuery('SELECT SUM(valor) FROM lancamentos WHERE tipo = "D"');

      if (resultReceita == null) {
        print("Esta vazio");
      } else {
        print("Não vazio");
      }

      print('resultado $resultReceita');
      print('teste2 $resultDespesa[0]');

      return resultReceita[0]["SUM(valor)"] - resultDespesa[0]["SUM(valor)"];
    }
  • Please put your formatted code exactly as you are using it (the one you posted wouldn’t even compile, are missing {}keys), and also put the stacktrace of the error that is occurring.

2 answers

1

Following the structure of your code, try using the .isEmpty

if (resultReceita.isEmpty)
  print("Esta vazio");
else
  print("Não vazio");

Explanation

Your database query may not be returning any record, but the object resultReceita was created, thus being different from NULL, so its validation did not work. In your case is returned a List<T> without any record, then the correct is to validate whether the list is empty or not.

Your code would look like this:

@override
Widget build(BuildContext context) {
//FUTURE BUILDER PARA EXIBIR SALDO CONTAS
Future<int> _query() async {
  var db = await DatabaseHelper.instance.database;
  var resultReceita = await db.rawQuery('SELECT SUM(valor) FROM lancamentos WHERE tipo = "R"');
  var resultDespesa = await db.rawQuery('SELECT SUM(valor) FROM lancamentos WHERE tipo = "D"');

  if (resultReceita.isEmpty)
    print("Esta vazio");
  else
    print("Não vazio");

  print('resultado $resultReceita');
  print('teste2 $resultDespesa[0]');

  return resultReceita[0]["SUM(valor)"] - resultDespesa[0]["SUM(valor)"];
}

0

Instead of using the keyword await , recommend to use in Future of the query to the Database the following:

db.rawQuery('SELECT SUM(valor) FROM lancamentos WHERE tipo = "R"').then((resultReceita) {
   if (resultReceita.isEmpty)
     debugPrint("Esta vazio");
   else
     debugPrint("Não vazio");

}).catchError((error) {
     debugPrint("ERRO");
     debugPrint(error.toString());
})

So you can understand exactly what is happening in the query, it is possible that an error is occurring by the value being Null (catchError) instead of a normal return (then).

After debugging and understanding the problem, you can use the await, but now knowing that the var resultReceita may be receiving an object of the type Error or Exception, instead of a Result database. Run the method .isEmpty() in a Error or Exception will generate an error and consequently will not access the following lines of code.

There are other possible approaches to capturing the error, such as wrapping your current code in a Try & Catch, I recommend you take a look over Utures to better understand at: https://dart.dev/codelabs/async-await

Ps: Use the debugPrint instead of print, if going to production it will not affect the user’s performance.

  • 1

    I find it unnecessary to use the then in this case. It is present in Dart only for backward compatibility. It is much more readable to use async/await for Utures and Try/catch errors.

  • You didn’t know that, backward compatibility with what exactly? I thought about this solution because I understand that it is easier to understand that an error is occurring, then as I said in the reply I recommended the article that indicates the Try & Catch you are talking about.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.