Flutter & Dio null safety issue in API Client: Bad Request 400

Issue

I am working on Flutter api client.
I use my own Django backend with dj-rest-auth package. I checked my backend via both browser and Postman, it seems it works properly. If I try to log in from my frontend simulator to my backend (dj-rest-auth), which run on the same device, I get:

Bad Request: /dj-rest-auth/login/
[08/Sep/2022 00:50:55] "POST /dj-rest-auth/login/ HTTP/1.1" 400 42

I tried:
[dio documentation][1]
[how to fix 400 Bad request][2](to check if my error is on backend side)
Unfortunately, I didn’t find more specific examples.

I saw the problem after I tried to meet the null security requirement in the following snippet (commented out the lines that gave an error related to null security, below them are two lines with which I unsuccessfully tried to fix the issue):

Future<AuthTokens?> refreshToken(BuildContext context) async {
    final AuthTokens? authTokens = await getCurrentTokens();
    if (authTokens == null) {
        return null;
    }
    return _dio
        .post(API_HOST + "jwt/refresh/",
            data: {'refresh': authTokens.refreshToken},
            options: Options(validateStatus: (status) => status! < 500))
            .then((response) {
                authTokens.accessToken = response.data['access'];
                if (response.data['access'] != null) {
                    authTokens.save();
                    return authTokens;
                }
            return null;
        });
    }    
    
    void login(password, email, Function(LoginResponse) callback) {
        print(password);
        _dio
            .post(API_HOST + "dj-rest-auth/login/",
                data: {
                    'email': email,
                    'password': password,
                },
                options: Options(validateStatus: (status) => status! < 500))
                .then((response) {
                    AuthTokens? authTokens = response.statusCode == 200
                        ? AuthTokens.fromJson(response.data)
                        : null;
              //authTokens?.save();
              //callback(new LoginResponse(response.statusCode, authTokens!));
                    if (authTokens != null) {authTokens.save();
                    callback(new LoginResponse(response.statusCode, authTokens));}
                    else {print('something');}
            });
    }

Perhaps more information is needed, if so, I’ll provide it. I would be grateful for any help.

Solution

The mistake is stupid, the answer is funny:-) Just look at:

void login(password, email, ...

The position of arguments is important in this case. When I swapped the password and email, everything worked fine.

Answered By – kokserek

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *