Huda
Huda

Reputation: 253

Convert Future<int> to int in flutter dart

I am using sqflite and I am getting rows count of specific record via below code:

  Future<int> getNumberOfUsers() async {
    Database db = await database;
    final count = Sqflite.firstIntValue(
        await db.rawQuery('SELECT COUNT(*) FROM Users'));
    return count;
  }
  Future<int> getCount() async {
    DatabaseHelper helper = DatabaseHelper.instance;
    int counter = await helper.getNumberOfUsers();
    return counter;
  }

I want to get the result of this function into int variable to use it inside onPressed in FloatingActionButton

int count = getCount();
int countParse = int.parse(getCount());
    return Stack(
      children: <Widget>[
        Image.asset(
          kBackgroundImage,
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          fit: BoxFit.cover,
        ),
        Scaffold(
          floatingActionButton: FloatingActionButton(
            backgroundColor: Colors.white,
            child: Icon(
              Icons.add,
              color: kButtonBorderColor,
              size: 30.0,
            ),
            onPressed: () {
              showModalBottomSheet(
                context: context,
                builder: (context) => AddScreen(
                  (String newTitle) {
                    setState(
                      () {
                        //--------------------------------------------
                        //I want to get the value here
                        int count = getCount();
                        int countParse = int.parse(getCount());
                        //--------------------------------------------
                        if (newTitle != null && newTitle.trim().isNotEmpty) {
                          _save(newTitle);
                        }
                      },
                    );
                  },
                ),
              );
            },
          ),

but I am getting this exception:

A value of type 'Future' can't be assigned to a variable of type 'int'.

Upvotes: 10

Views: 21169

Answers (4)

WAMA Learning
WAMA Learning

Reputation: 21

you need to add the "await" keyword before calling the function

int count = await getCount();

Upvotes: 1

Mirwais Shah Arya
Mirwais Shah Arya

Reputation: 369

All you need is to set the keyword "await" before calling the Future:

what you do:

int count = getCount(); 

what is correct:

int count = await getCount();

Upvotes: 3

Huda
Huda

Reputation: 253

I fixed this by adding async for OnPressed

onPressed: () async {...}

then use this line fo code

int count = await getCount();

thx

Upvotes: 11

Mary
Mary

Reputation: 517

use await to get response of Future

int number = await getNumberOfUsers();

int count = await getCount();

Upvotes: 2

Related Questions