Flutter Login API Request

Flutter Login API Request

Continue from previous tutorial: https://hashnotes.hashnode.dev/flutter-home-and-login-page

[1] Edit Login Screen

[1.1] Create HTTP POST Request (Multi Part Request)

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:hive/hive.dart';

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final Box _boxUser = Hive.box("user");

Future<void> _login() async {
  final url = Uri.parse('https://demo.razzi.my/spotnet/public/api/login');
  final request = http.MultipartRequest('POST', url);

  request.fields['email'] = _emailController.text;
  request.fields['password'] = _passwordController.text;

  final response = await request.send();
  final responseBody = await response.stream.bytesToString();

  if (response.statusCode == 200) {
    final data = jsonDecode(responseBody);
    final email = data['email'];
    final userToken = data['user_token'];

    // Update the 'boxUser' box
    await _boxUser.put('email', email);
    await _boxUser.put('user_token', userToken);

    // Handle the successful login response
    print(data);
    // Navigate to the home page
    Navigator.pushReplacementNamed(context, '/home');

  } else {
    // Handle the login error
    print('Login failed: $responseBody');
  }
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: _emailController,
              decoration: InputDecoration(
                labelText: 'Email',
              ),
            ),
            SizedBox(height: 16.0),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: InputDecoration(
                labelText: 'Password',
              ),
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: _login,
              child: Text('Login'),
            ),
          ],
        ),
      ),
    );
  }
}