Home > Enterprise >  capture value from login fields
capture value from login fields

Time:02-03

I'm facing a problem getting values ​​from the login field, I solved it, I'm using an elegant model, and I'm trying to modify it, seeing some examples I can't adapt to my problem.

main.dart file

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Login',
      theme: ThemeData(
        primaryColor: kPrimaryColor,
        scaffoldBackgroundColor: Colors.white,
      ),
      home: LoginScreen(),
    );
  }
}

my login.dart file

class LoginScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Body(),
    );
  }
}

they are in a separate file, I think it's better that way, but all the examples that I see people use practically inside a single file, the buttons are one for each file for that module

my file body.dart

class Body extends StatelessWidget {

  final TextEditingController usuarioController = TextEditingController();
  final TextEditingController _senhaController = TextEditingController();
/*  const Body({
    Key? key,
  }) : super(key: key);*/

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Background(
      child: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "LOGIN",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            SizedBox(height: size.height * 0.03),
            SvgPicture.asset(
              "assets/icons/login.svg",
              height: size.height * 0.35,
            ),
            SizedBox(height: size.height * 0.03),
            RoundedInputField(
              hintText: "Seu Email",
              onChanged: (value) {},
            ),
            RoundedPasswordField(
              onChanged: (value) {},
            ),
            RoundedButton(
              text: "LOGIN",
              callbackClickLogin: () {},
            ),
            SizedBox(height: size.height * 0.03),
          ],
        ),enter code here
      ),
    );
  }
}

I saw in an example that I need to define

final TextEditingController userController = TextEditingController();

to get data from the user field,

and final TextEditingController _passwordController = TextEditingController();

to get the password values.

and this is the click-to-login button

my file button_login.dart

class RoundedButton extends StatelessWidget {
  final text of the String;
  final Function() callbackClickLogin;
  final color Color, textColor;
  constRounded Button({
    Key? key,
    necessary this.text,
    required this.callbackClickLogin,
    this.color = kPrimaryColor,
    this.textColor = Colors.white,
  }) : super(key: key);

  @overlay
  Widget Build (BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10),
      width: size.width * 0.8,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(29),
        child: newElevatedButton(),
      ),
    );
  }

  //Used:ElevatedButton as FlatButton is deprecated.
  //Here we have to apply customizations to the Button inheriting the styleFrom

  newElevatedButton() widget {
    return HighButton(
      child: Text(
        text,
        style: TextStyle (color: textColor),
      ),
      onPressed: callbackClickLogin,
      style: ElevatedButton.styleFrom(
          primary color,
          padding: EdgeInsets.symmetric(horizontal: 40, vertical: 20),
          Text Style: Text Style(
              color: textColor, fontSize: 14, fontWeight: FontWeight.w500)
      ),
    );
  }
}

I don't know how to retrieve the values ​​when I click the login button, as I want to get the values ​​and pass them to another class in another file that will make a query via api.

I'm new to flutter.

thank you all.

CodePudding user response:

Can you show the code of RoundedInputField() ?

If I am not wrong , you probably have widget named RoundedInputField with TextField() inside it.

you must define your controller in that widget and pass the controller to TextField as:

  final TextEditingController userController = TextEditingController();

  TextField(
      //.........
      controller : userController,
   )

and you can retrieve the value as :

  final value = userController.text ;

CodePudding user response:

I'm new to flutter and I don't know if the practice I'm following is wrong, I did it like this: on my boot RoundedInputField for suario I passed the parameters controller:userController, and in it I recovered like this

child: TextField( controller:controller,

I have another problem now which is to use this data to do JWT authentication for my php server that I am using codeigniter 3 I don't know if it's right how I'm doing it or if it follows good practices inside my button

 RoundedButton( callbackClickLogin: () { 
Auth authentica = new Auth( 
           user:userController.text, password:passwordController.text, context: 
          context, ); authenticetica.login();
     } 
    ) 

in my auth file I have this code that I wrote

import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
class Auth {

  final String user;
  final String password;
  final BuildContext context;

  Auth({
    required this.user,
    required this.password,
    required this.context,
  });

  Future login() async {

    // header
    var header = {"alg":"HS256","typ":"JWT"};
    String header64 = base64Encode(jsonEncode(header).codeUnits);

    // payload clams
    var payload = {
        "sub":"1",
        "name":user,
        "exp":DateTime.now().millisecondsSinceEpoch   60000,
    };

    String payload64 = base64Encode(jsonEncode(payload).codeUnits);

    var secret = "app#Hbr%&Systems@";

    // signature
    var hmac = Hmac(sha256, secret.codeUnits);
    var digest = hmac.convert("$header64.$payload64".codeUnits);
    String sign = base64Encode(digest.bytes);
    print("$header64.$payload64.$sign");


  }    
}

before i had otherwise started communication with api:

/*Future login() async{
    if( user.isNotEmpty && password.isNotEmpty )
    {
      var url = "https://abcvendas.com/ci3/ApiApps/authUser";
      var response = await http.post(Uri.parse(url), body:({
        "email":username,
        "password":password,
      }));

      print("response: ");
      print(response.statusCode);
      if(response.statusCode == 200)
      {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text("Congratulations authenticated")));
      }else{
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text("Wrong login and password")));
      }
    }else{
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("Blank fields")));
    }

  }

  */

but we decided to switch to JWT and I can't progress

  •  Tags:  
  • Related