0

I'm getting a type 'Future<dynamic>' is not a subtype of type 'Future<String>'

I am simply trying to use a FutureBuilder in conjunction with SharedPreferences to return a string that I have previously stored using SharedPreferences.

Flutter : 'Future <dynamic>' is not a subtype of type bool

This stack overflow answer is doing the exact same thing as what I'm doing yet I have an error?

Widget build(BuildContext context) {

    return FutureBuilder<String>(
      future: getRoleFuture(),
      builder: (context, snapshot) {
        if(snapshot.data == false) {
          return Text("No data");
        }
        else {
          return Text(snapshot.data);
        }
      }
    );
  }

getRoleFuture() async {
    var sp = await SharedPreferences.getInstance();
    return sp.getString("role");
  }
Hamed
  • 5,867
  • 4
  • 32
  • 56
user9754798
  • 363
  • 3
  • 15

3 Answers3

2

The reason is that you used snapshot.data as bool in this line

if(snapshot.data == false) {
      return Text("No data");
    }

where as you set the Future return type as string maybe if you do this:

if(snapshot.data == null || snapshot.data == '') {
      return Text("No data");
    }
    else {
      return Text(snapshot.data);
    }
Qonvex620
  • 3,819
  • 1
  • 8
  • 15
0

Check the snapshot with hasData.

if(snapshot.hasData == false)

Gives the return type.

Future<String> getRoleFuture() async {
    var sp = await SharedPreferences.getInstance();
    return sp.getString("role");
  }
Kahou
  • 3,200
  • 1
  • 14
  • 21
0

In you FutureBuilder future pass a refrence to your function:

future: getRoleFuture, (without the parentheses)

so your code should be something like this:

Widget build(BuildContext context) {

return FutureBuilder<String>(
  future: getRoleFuture,
  builder: (context, snapshot) {
    if(!snapshot.hasData) {
      return Text("No data");
    }
    else {
      return Text(snapshot.data);
    }
  }
 );
}

Future<String> getRoleFuture() async {
var sp = await SharedPreferences.getInstance();
return sp.getString("role");
}

We don't use the parentheses in that code because we don't want the function to be called at the point where that code is encountered. Instead, we want to pass a reference to our function into the future.

Abdelbaki Boukerche
  • 1,602
  • 1
  • 8
  • 20