Login in Flutter using WordPress credentials

Solution:

Add the following code to your WordPress (either through your (child)theme’s functions.php, or by creating and enabling your own plugin):

add_action('rest_api_init', 'remoteLogin');

public static function remoteLogin($request = [])
{
    register_rest_route('remote-login', 'login', array(
        'methods' => 'POST',
        'callback' => 'restUserLogin',
    ));
}

function restUserLogin($request = [])
{
    $response = [
        'success' => false,
        'message' => 'Login failed'
    ];
    $status_code = 403;
    $parameters = $request->get_json_params();
    $username = sanitize_text_field($parameters['username']);
    $password = sanitize_text_field($parameters['password']);

    $user = null;
    if (!empty($username) && !empty($password)) {
        $user = wp_authenticate($username, $password);
    }

    if ($user instanceof WP_User) {
        $response['success'] = true;
        $response['message'] = 'Login successful';
        $status_code = 200;
    }

    return new WP_REST_Response($response, $status_code);
}

A new REST route named /remote-login/login has been created (you can change that in the register_rest_route call to whatever you like). The newly created REST route will also be listed on https://YOUR_DOMAIN_HERE/wp-json/ .

Next, you can POST a username and password from within your Flutter app like:

  var url = 'https://YOUR_DOMAIN_HERE/wp-json/remote-login/login';
  var body = jsonEncode({ 'username': 'USERNAME', 'password': 'SECRET' });
  http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  ).then((http.Response response) {
      final int statusCode = response.statusCode;
      if (statusCode == 200) {
         // login successful...

In this example, the status code is either 200, or 403. For 200, the login was successful so no need to even look at the success-part of the response JSON.