Register to aqueduct backend from Flutter frontend

378

Here is an example of connecting to an Aqueduct server from a Flutter client. (This isn't really a server question, though, since the client and server are independent of each other.)

Here is an example of registering:

void _register(String email, String password) async {
  Map<String, String> headers = {"Content-type": "application/json"};
  final jsonString = '{"username":"$email", "password":"$password"}';
  Response response = await post(YOUR_URL_HERE, headers: headers, body: jsonString);
  print('${response.statusCode} ${response.body}');
}

In your example you aren't encoding the JSON correctly.

And here is another example of signing in. The class is a view model architecture that I talk about here.

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

class LoginViewModel extends ChangeNotifier {

  String _token = '';
  bool _isLoggedIn = false;
  bool get isLoggedIn => _isLoggedIn;
  String get token => _token;

  Future onLoginPressed(String username, String password) async {
    if (username.isEmpty || password.isEmpty) {
      return;
    }
    _isLoggedIn = await _login(username, password);
    notifyListeners();
  }

  Future<bool> _login(String username, String password) async {
    var clientID = 'com.example.app';
    var clientSecret = '';
    var body = 'username=$username&password=$password&grant_type=password';
    var clientCredentials = Base64Encoder().convert('$clientID:$clientSecret'.codeUnits);

    Map<String, String> headers = {
      'Content-type': 'application/x-www-form-urlencoded',
      'authorization': 'Basic $clientCredentials'
    };
    var response = await http.post(YOUR_URL_HERE, headers: headers, body: body);
    final responseBody = response.body;
    if (response.statusCode != 200) {
      return false;
    }

    final map = json.decode(responseBody);
    _token = map['access_token'];
    return true;
  }
}
Share:
378
delmin
Author by

delmin

Updated on December 20, 2022

Comments

  • delmin
    delmin over 1 year

    I'm having a bit of difficulty with registering to aqueduct backend from my Flutter frontend

    Here is my code in my frontend:

      Future<void> signUp(String email, String password) async {
        final body = "username:$email,password:$password"; //<- return request entity could not be decoded
        //final body = {"username": email, "password": password}; //<- return bad state: Cannot set the body fields of Request with content-type "application/json"
    
        try {
          final http.Response response = await http.post(
              "http://localhost:8888/register",
              headers: {"Content-Type": "application/json"},
              body: body);
          final jsonResponse = json.decode(response.body);
          if (jsonResponse["error"] != null) {
            throw HttpException(jsonResponse["error"]);
          }
        } catch (error) {
          throw error;
        }
      }
    

    There must be some silly mistake. I believe it is with formatting body so I tried 2 options and both throw different http exception (as in comment).

  • delmin
    delmin about 4 years
    I actually know about login.. I was asking about registering... creating a new user
  • Suragch
    Suragch about 4 years
    Sorry, I just realized that too.
  • Suragch
    Suragch about 4 years
    @delmin, I updated my answer but I don't see what you did wrong.
  • delmin
    delmin about 4 years
    hmm... me neither.. I have basically same code as you have but I still get those error. can we actually save username in email format? That is the only difference in my code
  • delmin
    delmin about 4 years
    I got it... The format should be like this final body = '{"username": "$email", "password": "$password"}';
  • delmin
    delmin about 4 years
    BTW do you know how to delete a user.. Is it just about simple deleting him from user table?
  • Suragch
    Suragch about 4 years
    @delmin yes, I think so
  • delmin
    delmin about 4 years
    I just played to delete user with deleting him only from user table but that doesn't really work well. If a user is logged in or has token saved in his device then he can still login with that token.. I guess to delete user we have to delete him from the user table and also remove all his token which is explain in your question here stackoverflow.com/questions/56247509/…