Workshop: Flutter Auth Login #part5 LoginPage Get Access Token to set SharedPreferences

a sample API https://api.thana.in.th/workshop/documents

Login API :

https://api.thana.in.th/workshop/login

Test curl on Terminal

curl -X 'POST' \
  'https://api.thana.in.th/workshop/login' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "[email protected]",
  "password": "99999999"
}'

if ok status code = 200

Response body

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxMDQxOGQ3YWE4NTQyMDAxMmNiY2ZmMSIsImlhdCI6MTYyNzY2NzUxMCwiZXhwIjoxNjI3Njc5NTEwfQ.13PKvmz3jKgLMM7XkUBWH1TaQ3JceQEtTiOUFrlv9r8"
}

Login.dart

import 'dart:convert' as convert;
import 'package:http/http.dart';
class _LoginPageState extends State<LoginPage> {

...

_login(var values) async {
    var url = Uri.parse('https://api.thana.in.th/workshop/login');
    var response = await http.post(url,
        headers: {'Content-Type': 'application/json'},
        body: convert.jsonEncode(
            {'username': values['username'], 
             'password': values['password']
        }));
    var body = convert.jsonDecode(response.body);

    if (response.statusCode == 200) {
      final snackBar = SnackBar(content: Text('${values['username']} is Logged In'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    } else {
      final snackBar = SnackBar(content: Text(body['message']));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    }
  }

...

Login Button

 MaterialButton(
     onPressed: () {
     _formKey.currentState!.save();
     if (_formKey.currentState!.validate()) { 
       _login(_formKey.currentState!.value);
     } else {
       print("validation failed");
       }
     },
     child: Text("Login",
     style: TextStyle(color: Colors.blue)),
),

Run & Debug

Install shared_preferences

This will add a line like this to your package’s pubspec.yaml (and run an implicit dart pub get):


dependencies:
  shared_preferences: ^2.0.6

Import it

Now in your Dart code, you can use:

import 'package:shared_preferences/shared_preferences.dart';
...
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormBuilderState>();
  late SharedPreferences sharedPref;

  _initSharedPreferences() async {
    sharedPref = await SharedPreferences.getInstance();
  }

  @override
  void initState() {
    super.initState();
    _initSharedPreferences();
  }

...

Add Acess Token to shared_preferences

...
if (response.statusCode == 200) {

      ...

      //save token to pref
      await sharedPref.setString('token', response.body);
      print(sharedPref.getString('token'));
...

Run & Debug

Debug Console in VScode

getProfile API

https://api.thana.in.th/workshop/getprofile

test curl on Terminal

curl -X 'GET' \
  'https://api.thana.in.th/workshop/getprofile' \
  -H 'accept: application/json' \
  -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxMDQxOGQ3YWE4NTQyMDAxMmNiY2ZmMSIsImlhdCI6MTYyNzY3NDA0MiwiZXhwIjoxNjI3Njg2MDQyfQ.ahc01R6zB2_lqfeFIqqMOQ-6XxFYAHBrrHpATBET2VM'

if ok status code = 200

Response body

{"username":"[email protected]","name":"Obi-Wan","surname":"Kenobi"}

get Profile to shared_preferences

 _login(var values) async {
    var url = Uri.parse('https://api.thana.in.th/workshop/login');
    var response = await http.post(url,
        headers: {'Content-Type': 'application/json'},
        body: convert.jsonEncode(
            {'username': values['username'], 'password': values['password']}));
    var body = convert.jsonDecode(response.body);

    if (response.statusCode == 200) {
  
    ...

      _getProfile(body);
      
    } else {

    ...
 _getProfile(var token) async {
    //http get profile
    var url = Uri.parse('https://api.thana.in.th/workshop/getprofile');
    var response = await http.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer ${token['access_token']}',
      },
    );
    var body = convert.jsonDecode(response.body);

    if (response.statusCode == 200) {
      print('statusCode == 200');
      //save profile to pref
      await sharedPref.setString('profile', response.body);
      print(sharedPref.getString('profile'));

      //open Launcher
      Navigator.pushNamed(context,'/launcher',);

    } else {
      print('get profile fail');
      print(body['message']);
    }
  }

Run & Debug

Debug Console in VScode

(Visited 165 times, 1 visits today)
Spread the love