title: Error in Flutter: type 'string' is not a subtype of type 'map<string, dynamic>?' in type cast
body: <p>I'm trying to built an app for my college degree with flutter that has a login screen where you insert the username and password and pass to the main screen. I use retrofit for the REST API. When  I press the login button with the credentials I get the error: <code>Exception: DioError [DioErrorType.other]: type 'String' is not a subtype of type 'Map&lt;String, dynamic&gt;?' in type cast.</code>
  I'm very new in Flutter can you help me? Here is my code:</p>
  <p><strong>Api_Service</strong></p>
  <pre><code>@RestApi(baseUrl: '...')
  abstract class ApiService {
    factory ApiService(Dio dio, {required String baseUrl}) {
      dio.options = BaseOptions(
          receiveTimeout: 3000,
          connectTimeout: 3000,
          contentType: 'application/json',
          headers: &lt;String, String&gt;{
            'Authorization': 'Basic Y29hY2g6Y29hY2g=',
            'Accept': 'application/json',
          },
          followRedirects: false,
          validateStatus: (status) {
            return status! &lt; 400;
          });
      return _ApiService(dio, baseUrl: baseUrl);
    }
  
    //Login Service
    @POST('...')
    @FormUrlEncoded()
    Future&lt;LoginResponse&gt; login(@Body() Map&lt;String, dynamic&gt; body);
  </code></pre>
  <p><strong>Api_Response</strong></p>
  <pre><code>@JsonSerializable()
  class LoginResponse {
    //show login response data
  
    @JsonKey(name: 'Status')
    final int statusCode;
  
    @JsonKey(name: 'Message')
    final String message;
  
    @JsonKey(name: 'Content')
    final UserEntity userEntity;
  
    LoginResponse(this.statusCode, this.message, this.userEntity);
  
    factory LoginResponse.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
        _$LoginResponseFromJson(json);
  
    Map&lt;String, dynamic&gt; toJson() =&gt; _$LoginResponseToJson(this);
  }
  </code></pre>
  <p><strong>User_entity</strong></p>
  <pre><code>import 'package:json_annotation/json_annotation.dart';
  part 'user_entity.g.dart';
  //done this file
  @JsonSerializable()
  class UserEntity {
    @JsonKey(name: 'id')
    final String id;
    @JsonKey(name: 'username')
    final String username;
    @JsonKey(name: 'role')
    final String role;
    UserEntity(this.id, this.username, this.role);
    factory UserEntity.fromJson(Map&lt;String, dynamic&gt; json) =&gt;
        _$UserEntityFromJson(json);
    Map&lt;String, dynamic&gt; toJson() =&gt; _$UserEntityToJson(this);
  }
  </code></pre>
  <p><strong>User</strong></p>
  <pre><code>class User {
    String? id;
    String? username;
    String? role;
    String? token;
    String? renewalToken;
  
    User({this.id, this.username, this.role, this.token, this.renewalToken});
  
      factory User.fromJson(Map&lt;String, dynamic&gt; responseData) {
          return User(
            id: responseData['id'],
            username: responseData['username'],
            role: responseData['role'],
            token: responseData['token'],
            renewalToken: responseData['token'],
          );
        }
  </code></pre>
  <p><strong>User_provider</strong></p>
  <pre><code>    class UserProvider extends ChangeNotifier {
    User _user = User();
  
    User get user =&gt; _user;
  
    void setUser(User? user) {
      _user = user!;
      notifyListeners();
    }
  }
  </code></pre>
  <p><strong>Auth_provider</strong></p>
  <pre><code>enum Status { NotLoggedIn, LoggedIn, Authenticating, LoggedOut }
  
  class AuthProvider extends ChangeNotifier {
    Status _loggedInStatus = Status.NotLoggedIn;
  
    Status get loggedInStatus =&gt; _loggedInStatus;
  
    set loggedInStatus(Status value) {
      _loggedInStatus = value;
    }
  
    static Future&lt;FutureOr&gt; onValue(Response response) async {
      var result;
  
      final Map&lt;String, dynamic&gt; responseData = json.decode(response.body);
  
      print(responseData);
  
      if (response.statusCode == 200) {
        // now we will create a user model
        User authUser = User.fromJson(responseData);
  
        // now we will create shared preferences and save data
        UserPreferences().saveUser(authUser);
  
        result = {
          'status': true,
          'message': 'Successfully registered',
          'data': authUser
        };
      } else {
        result = {
          'status': false,
          'message': 'Successfully registered',
          'data': responseData
        };
      }
      return result;
    }
  
    Future&lt;Map&lt;String, dynamic&gt;&gt; login(String username, String password) async {
      var result;
  
      Map&lt;String, dynamic&gt; loginData = {
        'Username': username,
        'Password': password,
      };
  
      _loggedInStatus = Status.Authenticating;
      notifyListeners();
  
      ApiService apiService = ApiService(dio.Dio(), baseUrl: '');
  
      final response = await apiService.login(loginData);
  
      print('${response.toJson()}');
  
      if (response.statusCode == 200) {
  
        User authUser = User(
          id: response.userEntity.id,
          username: response.userEntity.username,
          role: response.userEntity.role,
        );
  
        UserPreferences().saveUser(authUser);
  
        _loggedInStatus = Status.LoggedIn;
        notifyListeners();
  
        result = {'status': true, 'message': 'Successful', 'user': authUser};
      } else {
        _loggedInStatus = Status.NotLoggedIn;
        notifyListeners();
        result = {'status': false, 'message': ''};
      }
  
      return result;
    }
  
    onError(error) {
      print('the error is ${error.detail}');
      return {'status': false, 'message': 'Unsuccessful Request', 'data': error};
    }
  }
  </code></pre>
  <p><strong>Main</strong></p>
  <pre><code>class MyApp extends StatelessWidget {
    const MyApp({Key? key}) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
      Future&lt;User&gt; getUserData() =&gt; UserPreferences().getUser();
  
      return MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (_) =&gt; AuthProvider()),
            ChangeNotifierProvider(create: (_) =&gt; UserProvider())
          ],
          child: MaterialApp(
            theme: ThemeData(
              backgroundColor: Color(0Xfff7f7f5),
              fontFamily: 'Cera',
              appBarTheme: AppBarTheme(
                backgroundColor: Colors.white,
              ),
            ),
            debugShowCheckedModeBanner: false,
            // home: LoginScreen(),
            home: FutureBuilder&lt;User&gt;(
                future: getUserData(),
                builder: (context, snapshot) {
                  switch (snapshot.connectionState) {
                    case ConnectionState.none:
                    case ConnectionState.waiting:
                      return CircularProgressIndicator();
                    default:
                      if (snapshot.hasError)
                        return Text('Error: ${snapshot.error}');
                      else if (snapshot.data!.token == null) {
                        return LoginScreen();
                      } else
                        Provider.of&lt;UserProvider&gt;(context).setUser(snapshot.data);
                        return TeamsScreen();
                  }
                }),
            routes: {
              '/auth': (context) =&gt; LoginScreen(),
              '/teams': (context) =&gt; TeamsScreen(),
            },
          ));
    }
  }
  </code></pre>
  <p><strong>shared_preferences</strong></p>
  <pre><code>class UserPreferences {
    Future&lt;bool&gt; saveUser(User user) async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
  
      prefs.setString('id', user.id as String);
      prefs.setString('username', user.username as String);
      prefs.setString('role', user.role as String);
      prefs.setString('token', user.token as String);
      return saveUser(user);
    }
  
    Future&lt;User&gt; getUser() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
  
      String id = prefs.getString(&quot;id&quot;) ?? '';
      String username = prefs.getString(&quot;username&quot;) ?? '';
      String role = prefs.getString(&quot;role&quot;) ?? '';
      String token = prefs.getString(&quot;token&quot;) ?? '';
      String renewalToken = prefs.getString(&quot;renewalToken&quot;) ?? '';
  
      return User(
          id: id,
          username: username,
          role: role,
          token: token,
          renewalToken: renewalToken);
    }
  
    void removeUser() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
  
      prefs.remove('id');
      prefs.remove('username');
      prefs.remove('role');
      prefs.remove('token');
    }
  
    Future&lt;String?&gt; getToken() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      String? token = prefs.getString(&quot;token&quot;);
      return token;
       
  
   }
  }
  </code></pre>