Home > Software design >  I can't get the return value from a function
I can't get the return value from a function

Time:06-14

I have a class called TotalLabel() that gets a double value from another function:

Future<double> getValue(String type) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    double total = prefs.getDouble(type) ?? 0;
    return total;
  } 

This is how I call the function to get the result:

TotalLabel(
                typeOf: 'Hidrats de carboni',
                subtitle: 'Range',
                onPressed: () {},
                fillBar:
                    getValue('hidratsDeCarboni') //gets result from function
                )

The problem is that when I call the function passing the ID of the variable that I want to get, I have this error: "The argument type 'Future can't be assigned to the parameter type double".

Error

Thanks.

CodePudding user response:

getValue returns a Future<double> so you either await for it in the initState or use a FutureBuilder

FutureBuilder<double>(
  future: getValue('hidratsDeCarboni'),
  builder: (context, snapshot) {
    if(snapshot.connectionState != ConnectionState.done) {
      return CircularProgressIndicator();
    } else if(!snapshot.hasError && snapshot.hasData) {
      return TotalLabel(
        typeOf: 'Hidrats de carboni',
        subtitle: 'Range',
        onPressed: () {},
        fillBar: snapshot.data!,
      );
    } else {
      return const Text('error');
    }
  }
)

CodePudding user response:

you are returning the value from a future function you need to use await to wait for a response then use that value.

  • Related