Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type 'Future<String>' is not a subtype of type 'String' in type cast in flutter

Tags:

flutter

dart

I used following function to get user Id from web service

Future<String> getUserid() async {
  final storage = new FlutterSecureStorage();
  // Read value
  String userID = await storage.read(key: 'userid');
  return userID;
}

when useing this function error occured

type 'Future' is not a subtype of type 'String' in type cast

this is what i have tried

otherFunction() async {

  final String userID = await getUserid();
 return userID;
}

Future<String> getUserid() async {
  final storage = new FlutterSecureStorage();
  // Read value
  String userID = await storage.read(key: 'userid');
  return userID;
}

print(otherFunction());

still error msg shows as

I/flutter (18036): Instance of 'Future'

like image 427
sampath Avatar asked Apr 18 '19 09:04

sampath


1 Answers

You will need to await your function. If you are totally unaware of Future's in Dart, you should read through this comprehensive article.

In Flutter, there are now two ways to handle this case. Either you want to call your function in a regular other function. In that case, you would either mark that function as async or use getUserid().then((String userID) {...}). If you were to use async, you would need to use await as well:

otherFunction() async {
  ...
  final String userID = await getUserid();
  ...
}

However, in Flutter it is very likely that you want to use your value in the build method of your widget. In that case, you should use a FutureBuilder:

@override
Widget build(BuildContext context) {
  return FutureBuilder(future: getUserid(),
                       builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                         if (!snapshot.hasData) return Container(); // still loading
                         // alternatively use snapshot.connectionState != ConnectionState.done
                         final String userID = snapshot.data;
                         ...
                         // return a widget here (you have to return a widget to the builder)
                       });
}
like image 177
creativecreatorormaybenot Avatar answered Nov 01 '22 17:11

creativecreatorormaybenot