Search code examples
flutterdartauthorizationtokenrest

How can I get token response with username and password textfields? dart/flutter


I'm kind of new to rest api and flutter. I wanna login with the username and password and get the token response. How can I get the username and password from the text field for authorization? I'm also not sure about the auth code is correct?

imports

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {

  final  usernameController = TextEditingController();
  final  passwordController = TextEditingController();

Future<String> authorization() async {
    var request = http.MultipartRequest(
        'POST', Uri.parse('url'));
    request.fields.addAll({
      'grant_type': 'info',
      'client_id': 'info',
      'username': username,
      'password': password,
    });

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      Map<String, dynamic> auth =
          jsonDecode(await response.stream.bytesToString());

      return auth['access_token'];
    } else {
      return "";
    }
  }

  void _setText() {
    setState(() {
      username = usernameController.text;
      password = passwordController.text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          Padding(
            child: TextField(
              decoration: InputDecoration(labelText: 'username'),
              controller: usernameController,
            ),
          ),
          Padding(
            child: TextField(
              decoration: InputDecoration(labelText: 'password'),
              controller: passwordController,
            ),
          ),          
          RaisedButton(
            onPressed: _setText,
            child: Text('Login'),
          ),
        ],
      ),
    );
  }
}

Solution

    • Since you are using TextEditingControllers, you won't have to use Strings to hold the values of username and password.

    change them like this:

      TextEditingController usernameController = TextEditingController();
      TextEditingController  passwordController = TextEditingController();
    

    Then, change your API post to this:

    Future<String> authorization() async {
        var request = http.MultipartRequest(
            'POST', Uri.parse('url'));
        request.fields.addAll({
          'grant_type': 'info',
          'client_id': 'info',
          'username': usernameController.text, //notice you have to use .text
          'password': passwordController.text, //notice you have to use .text
        });
    
    • Your onPressed like this:

      RaisedButton(
      onPressed: () async {
      String token = await authorization();
      print(token); //This will be your token.
      },
      child: Text('Login'),),
      
    • you don't need this anymore:

      //void _setText() {
      //setState(() {
      //username = usernameController.text;
      // password = passwordController.text;
      //});
      //}