flutter login using an api

Viewed 7812

I'm trying to consume an API for the login screen but keep getting this error. I want to be able to login via an API to my flutter app. the first part is what is being posted to the API and the second part is the server response as seen on the code below


    I/flutter (  892): {email: rashid.david12@gmail.com, password: 123456789}
    I/flutter (  892): {errors: [The email field is required., The password field is required.]}

This is my code, what should I do, or any workaround for the error above?


    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    class Signin extends StatefulWidget {
      @override
      _SigninState createState() => _SigninState();
    }
    
    class _SigninState extends State<Signin> {
      // For CircularProgressIndicator.
      bool visible = false ;
    
      // Getting value from TextField widget.
      final emailController = TextEditingController();
      final passwordController = TextEditingController();
    
      Future userLogin() async{
    
        // Showing CircularProgressIndicator.
        setState(() {
          visible = true ;
        });
    
        // Getting value from Controller
        String email = emailController.text;
        String password = passwordController.text;
    
        // SERVER LOGIN API URL
        var url = 'http://192.236.160.238/api/login';
    
        // Store all data with Param Name.
        var data = {'email': email, 'password' : password};
    
        // Starting Web API Call.
        var response = await http.post(url, body: json.encode(data[email]));
        print(data);
    
        // Getting Server response into variable.
        var message = jsonDecode(response.body);
        print(message);
    
        // If the Response Message is Matched.
        if(message == 'success')
        {
    
          // Hiding the CircularProgressIndicator.
          setState(() {
            visible = false;
          });
    
          // Navigate to Home & Sending Email to Next Screen.
          Navigator.pushNamed(context, '/home');
        }else{
    
          // If Email or Password did not Matched.
          // Hiding the CircularProgressIndicator.
          setState(() {
            visible = false;
          });
    
          // Showing Alert Dialog with Response JSON Message.
          // showDialog(
          //   context: context,
          //   builder: (BuildContext context) {
          //     return AlertDialog(
          //       title: new Text(message),
          //       actions: <Widget>[
          //         FlatButton(
          //           child: new Text("OK"),
          //           onPressed: () {
          //             Navigator.of(context).pop();
          //           },
          //         ),
          //       ],
          //     );
          //   },
          // );
          }
    
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            leading: Icon(Icons.menu),
            title: const Text('Bdm Self Service App'),
            centerTitle: true,
            actions: [
          Padding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          child: Icon(Icons.search),
          ),
          ],
            backgroundColor: Colors.blue,
            elevation: 0.0,
          ),
          body: Padding(
            padding: EdgeInsets.fromLTRB(30.0, 40.0, 30.0, 0.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Center(
                  child: CircleAvatar(
                    backgroundImage: AssetImage('assets/rcmsbg.png'),
                    radius: 60.0,
                  ),
                ),
                SizedBox(height: 10.0),
                TextFormField(
                controller: emailController,
                  decoration: InputDecoration(labelText: 'Enter Username or Email'),
                ),
                SizedBox(height: 10.0),
                TextFormField(
                controller: passwordController,
                  decoration: InputDecoration(labelText: 'Enter Password'),
                  autofocus: false,
                  obscureText: true,
                ),
                SizedBox(height: 20.0),
                FlatButton(
                  shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                  side: BorderSide(color: Colors.green)),
                  onPressed: userLogin,
                  child: Text('login'),
                  color: Colors.green,
                  minWidth: 300.0,
                ),
                SizedBox(height: 20.0),
                Text('Forgot Password?'),
                FlatButton(
                  shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                  side: BorderSide(color: Colors.green)),
                  onPressed: () {
                    Navigator.pushNamed(context, '/resetpassword');
                  },
                  child: Text('Reset Password'),
                  color: Colors.green,
                  minWidth: 200.0,
                ),
                SizedBox(height: 20.0),
                Text('Do not have an account yet?'),
                FlatButton(
                  shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18.0),
                  side: BorderSide(color: Colors.green)),
                  onPressed: () {
                    Navigator.pushNamed(context, '/signup');
                  },
                  child: Text('Sign Up'),
                  color: Colors.green,
                  minWidth: 200.0,
                ),
              ],
            ),
            // ],
          ),
          // ),
        );
      }
    }

2 Answers

If I am reading your code correctly, on the login function you are only sending email and

        // Store all data with Param Name.
        var data = {'email': email, 'password' : password};
    
        // Starting Web API Call.
        var response = await http.post(url, body: json.encode(data)); // REMOVED [email]
        print(data);

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:http/http.dart';
class SignUpScreen extends StatefulWidget {
  const SignUpScreen({Key? key}) : super(key: key);

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

class _SignUpScreenState extends State<SignUpScreen> {

  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  void login(String email , password) async {
    
    try{
      
Response response = await post(
        Uri.parse('https://reqres.in/api/login'),
        body: {
          'email' : 'eve.holt@reqres.in',
          'password' : 'cityslicka'
        }
      );

      if(response.statusCode == 200){
        
        var data = jsonDecode(response.body.toString());
        print(data['token']);
        print('Login successfully');

      }else {
        print('failed');
      }
    }catch(e){
      print(e.toString());
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sign Up Api'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextFormField(
              controller: emailController,
              decoration: InputDecoration(
                hintText: 'Email'
              ),
            ),
            SizedBox(height: 20,),
            TextFormField(
              controller: passwordController,
              decoration: InputDecoration(
                  hintText: 'Password'
              ),
            ),
            SizedBox(height: 40,),
            GestureDetector(
              onTap: (){
                login(emailController.text.toString(), passwordController.text.toString());
              },
              child: Container(
                height: 50,
                decoration: BoxDecoration(
                  color: Colors.green,
                  borderRadius: BorderRadius.circular(10)
                ),
                child: Center(child: Text('Login'),),
              ),
            )
          ],
        ),
      ),
    );
  }
}
Related