Flutter login screen and form verification

Gif renderings first

Gif may not move in nuggets, please right click, open in a new TAB, or click below [Click to open Gif]

Open GIF

So let’s draw the UI, and then we’ll do the validation, and now we’ve drawn the UI, and we’ve talked about the layout before, and if you can’t, you can read the previous article.

When the user logs in, he or she has to enter his or her mobile phone number or something. This is done with the Form Form that comes with Flutter

First use the Form component function (widget, to be exact), then write a key, because we’re going to manipulate it later, and then write a Child, inside which is the TextFormField component.

TextFormField has a validator function that accepts a value as an input parameter and returns a null as an error.

Take a look at the complete code

Everybody, give it a thumbs up as you watch it, if it helps. “Like” doesn’t do me any good, but I want to feel everyone’s warm love ~ ~

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cjyy/utils/http.dart';
import 'package:cjyy/utils/toast.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  static String tag = 'login-page';
  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Jverify jverify = new Jverify();
  List<JVCustomWidget>widgetList = [];
  JVUIConfig uiConfig = JVUIConfig();
  
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  String _phone = ' ';
  String _pw = ' '; // Password display, hide bool _isObscure =true;
  Color _eyeColor = Colors.grey;

  final _phone_controller = TextEditingController();

  @override
  void initState() {
    // SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor: Colors.transparent,statusBarIconBrightness:Brightness.dark);
    // SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);

    _phone_controller.addListener((){
      // debugPrint('input:${_phone_controller.text}');
    });
    super.initState();
  }
  @override
  void dispose() {
    _phone_controller.dispose();
    super.dispose();
  }
  
  void _onSubmit() async{
    final form = _formKey.currentState;
    if(form.validate()) {
      form.save();
      // showDialog(context: context, builder: (ctx)=> new AlertDialog(
      //   content:  new Text('phone: $_phone , pw: $_pw '),
      // ));
      String response_content = await HTTP('get:phone_pw_login', {
        "phone": _phone,
        "pass": _pw
      });
      Map<String, Object> response_map = jsonDecode(response_content);
      if(response_map['code']! = 200) {print('Login exception');
        Toast.show('Login exception', context);
        return;
      }
      Map<String, Object> data = response_map['data'];
      final prefs = await SharedPreferences.getInstance();
      final setTokenResult = await prefs.setString('user_token', data['token']);
      await prefs.setInt('user_phone', data['phone']);
      await prefs.setString('user_name', data['name']);
      if(setTokenResult){
        debugPrint('Login token saved successfully');
        Navigator.of(context).pushReplacementNamed('/');
      }else{
        debugPrint('error, failed to save login token ');
      }
    }
  }
  onRigister() async{
    final result = await Navigator.pushNamed(context, '/rigister');
    print(result);
    _phone_controller.text = result;
  }
  @override
  Widget build(BuildContext context) {
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,statusBarIconBrightness:Brightness.dark,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    final logo = new Hero(
      tag: 'hero', child: new CircleAvatar(backgroundColor: Colors. Transparent, RADIUS: 48.0, Child: new ClipRRect(Child: new SizedBox( width: 120, height: 120, child: new Image.asset('images/cjyy_320.jpg', fit: BoxFit.cover),
          ),
          borderRadius: BorderRadius.all(Radius.circular(15))
        ),
      ),
    );

    final phone = new TextFormField(
      keyboardType: TextInputType.number,
      autofocus: false,
      // initialValue: ' ',
      controller: _phone_controller,
      onSaved: (val)=> this._phone = val,
      validator: (value){
        if(value.length ! 11) = {return 'Mobile phone number does not exist.';
        }else{
           return null;
        }
      },
      decoration: new InputDecoration(
        hintText: 'Mobile phone Number',
        contentPadding: new EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: new OutlineInputBorder(
          borderRadius: BorderRadius.circular(32.0)
        )
      )
    );

    final password = new TextFormField(
      autofocus: false,
      initialValue: ' ',
      onSaved: (val)=> this._pw = val,
      obscureText: _isObscure,
      validator: (value){
        if(value.length < 6 || value.length > 16){
          return 'Password between 6 and 16 digits.';
        }else{
           return null;
        }
      },
      decoration:  new InputDecoration(
        hintText: 'password', contentPadding: new EdgeInsets. FromLTRB (20.0, 10.0, 20.0, 10.0), border: new OutlineInputBorder(borderRadius: BorderRadius. Circular (32.0)), suffixIcon: IconButton(icon: icon (Icons. Remove_red_eye, color: _eyeColor, ), onPressed: () {setState(() { _isObscure = ! _isObscure; _eyeColor = _isObscure ? Colors.grey : Theme.of(context).iconTheme.color; }); }),),); Final loginButton = new Padding(Padding: new EdgeInsets. Symmetric (vertical: 16.0), child: Container(width: 0) double.infinity, height: 45, margin: EdgeInsets.only(top: 50,left: 10,right: 10), child: RaisedButton( onPressed: () { debugPrint('QAQ');
                  _onSubmit();
                },
                shape: StadiumBorder(side: BorderSide.none),
                color: Color(0xff44c5fe),
                child: Text(
                  'login',
                  style: TextStyle(color: Colors.white,fontSize: 15),
                ),
              ),
            ),
    );

    final forgetLabel = new FlatButton(
      onPressed: (){
        print('Wait to die.');
      },
      child: new Text('Forget your password? ',style: new TextStyle(color: Colors.black54),),
    );
    final registerLabel = new FlatButton(
      onPressed: onRigister,
      child: new Text('registered',style: new TextStyle(color: Colors.black54),),
    );
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: new Scaffold(
        backgroundColor: Colors.white,
        body: new Center(
          child: new Center(
            child: new ListView(
              shrinkWrap: true, padding: new EdgeInsets. Only (left: 24.0,right: 24.0), children: <Widget>[new Form(key: _formKey, child: New Column(children: <Widget>[logo, SizedBox(height: 48.0), phone, SizedBox(height: 8.0), Password, SizedBox(height: 48.0) 24.0,), loginButton, / / forgetLabel registerLabel,],),),),),),)); }}Copy the code

–END–