Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep returning "Instance of 'Future<dynamic>" instead of String (Flutter)

Tags:

flutter

dart

I've looked everywhere and found no solution. I'm wanting to return the result count from a query, yet I'm having troubles. Keep getting "Instance of 'Future" instead of String

I'm using the Singleton pattern.

  • DB method (database.dart):
    Future<int> getUnCompletedTaskCount () async {
    final db = await database;
    var result = await db.rawQuery("SELECT * FROM Tasks WHERE isComplete = 0");
    int count = Sqflite.firstIntValue(result);
    return count;
  }
  • My method in main.dart:
    getResultCount () async {
    final value = await DBProvider.db.getUnCompletedTaskCount();
    return value;
  }
  • Calling the method by:
    getResultCount().toString()
like image 296
Jonathon Avatar asked Oct 23 '25 22:10

Jonathon


1 Answers

I don't know how You're going to use this function, If you need it to get number of completed tasks and then draw something on screen(Like show a list of them or show number of them), I myself use FutureBuilder,Like Below:

FutureBuilder<int>(
  future: getResultCount(),
  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
    if(snapshot.hasData){
      return Text('Number Of completed : ${snapshot.data}');
    }
    return Container();
  },
)

So when it completely fetch it, it shows a Text Widget, Otherwise it shows nothing(empty Container)

But if you need it in lets say an equation or something, you can do something like this:

  await getResultCount().then((val){
      // do some operation
    });

But again it totaly depends on your code and need.

When you need result of a future function in your code use await before it.

Like getResultCount() use await when You need to use the result of it.

like image 193
NoobN3rd Avatar answered Oct 26 '25 12:10

NoobN3rd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!