Home > Blockchain >  Expected a value of type 'Map<String, Object>', but got one of type '_JsonMap&#
Expected a value of type 'Map<String, Object>', but got one of type '_JsonMap&#

Time:10-14

after updating Flutter to null safety I got Expected a value of type 'Map<String, Object>', but got one of type ' error.

 Future<bool> tryAutoLogin() async {
    final prefs = await SharedPreferences.getInstance();
     if (!prefs.containsKey('userData')) {
       return false;
     }
    try {
      final extractedUserData =
          json.decode(prefs.getString('userData')as String) as Map<String, Object>;
      print(extractedUserData);
    } catch (error) {
      print(error);
    }
   
    return true;
  }


Does anyone know why it is happening? Thank you in advance.

CodePudding user response:

In dart, there is a difference between the type Object vs the keyword dynamic. What is the difference? Take a look at this. Now, if jsonDecode receives a Map then it returns a Map<String, dynamic> to allow for calling methods that aren't defined for Object.

Solution: Replace Map<String, Object> with Map<String, dynamic>.

Also, here is a code style hint: Don't cast a String? by using as String, use ! after the nullable value to assume it not being null.

  • Related