[Solved] Map keeps returning null values

Question

Asked by squnk on December 23, 2021 (source).

I have an issue with creating POST request. No matter what I input, I keep getting null as email and password.

class _LoginPageState extends State<LoginPage> {
  late LoginRequestModel requestModel;

  @override
  void initState() {
    super.initState();
    requestModel = LoginRequestModel();
  }

I have two TextFormFields where I added onSaved: (input) => requestModel.email = input

Then whenever when input values and I submit on my button it keeps printing {email: null, password: null }

print(requestModel.email); //null
import 'package:flutter/foundation.dart';

class LoginRequestModel {
   String? email;
   String? password;

  LoginRequestModel({ this.email, this.password} );

  factory LoginRequestModel.fromJson(Map<String, dynamic> json) {
      return LoginRequestModel(
        email: json['email'],
        password: json['password']
    );
    }
}
class Auth {
  static String baseUrl = "MY_API";

  var client = http.Client();

  void login(LoginRequestModel model) async {
     await client.post(Uri.parse(baseUrl), body: model);
  }

}
TextFormField(
                cursorColor: Colors.black,
                obscureText: false,
                onSaved: (input) => requestModel.email = input,

How do I successfully make a POST request?

Answer

Question answered by Jahidul I (source).

Simply you can do with the TextEditingController for responsive input and for post network call you need to jsonEncode

class ResponsiveInput extends StatelessWidget {
  ResponsiveInput({Key key}) : super(key: key);
  TextEditingController emailTextEditingController = TextEditingController();
  TextEditingController passwordTextEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(left: 30, right: 30),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextFormField(
            controller: emailTextEditingController,
            cursorColor: Colors.black,
            obscureText: false,
            onSaved: (input) {},
          ),

          TextFormField(
            controller: passwordTextEditingController,
            cursorColor: Colors.black,
            obscureText: false,
            onSaved: (input) {},
          ),

          TextButton(onPressed: (){
            LoginRequestModel login = LoginRequestModel(
              email: emailTextEditingController.text,
              password: passwordTextEditingController.text,

            );

            Auth().login(login);

          }, child: Text("Login"))
        ],
      ),
    );
  }
}

For complete source code: link

output:

enter image description here

enter image description here

FLUTTER
SHARE: