Всем привет и добро пожаловать в новую серию руководств по Flutter. Сегодня мы узнаем, как создать простую страницу регистрации с проверкой формы / пользовательским интерфейсом с помощью Flutter.

Сегодня форма играет жизненно важную роль в любом мобильном приложении. Практически во всех приложениях в мире есть форма для заполнения.

Обзор этого руководства.
В этом приложении будет 5 текстовых полей, состоящих из:
→ Полное имя
→ Адрес электронной почты
→ Номер телефона
→ Пароль
→ Подтвердить пароль
и кнопку отправки для проверки.
Если вводимые пользователем данные недействительны в соответствии с установленными нами правилами, мы просто отобразим закусочную, содержащую сообщение об ошибке. например, недействительный адрес электронной почты, как показано ниже.

Давайте теперь погрузимся в кодирование !!!

Создание нашего UI (пользовательского интерфейса).

Создайте новый проект флаттера и удалите весь сгенерированный код в файле main.dart. Сначала импортируйте пакет материалов

import 'package:flutter/material.dart';

Затем определите основную функцию, подобную этой, с помощью виджета без сохранения состояния под названием MyApp:

void main() {
   runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       title: 'Flutter Beginner Tutorial',
       theme: ThemeData(
         primarySwatch: Colors.green,
         visualDensity: VisualDensity.adaptivePlatformDensity,
       ),
       home: MyHomePage(),
    );
  }
}

При создании S tatefulWidget для MyHomePage () он должен выглядеть так:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Итак, в _MyHomePageState extends State мы собираемся объявить контроллер для каждого из наших полей формы:

TextEditingController _name = TextEditingController();
TextEditingController _email = TextEditingController();
TextEditingController _phn = TextEditingController();
TextEditingController _pass = TextEditingController();
TextEditingController _cpass = TextEditingController();
// we declare a _ScaffoldState here called _formKey because we're going to change the state of the app by showing the snack bar
var _formKey = GlobalKey<ScaffoldState>();
bool hidePass = true; // this is probably for showing and hiding our password

В виджете сборки вместо того, чтобы возвращать виджет контейнера, мы собираемся вернуть виджет Scaffold (), полный код:

Scaffold(
      key: _formKey,
      appBar: AppBar(
        title: Text('Simple Form Validation'),
        centerTitle: true,
        elevation: 0,
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Center(
                child: Text(
                  'Register Page',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w300,
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.all(20),
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      controller: _name, // the controller we declared at the top
                      decoration: InputDecoration(
                        icon: Icon(Icons.person),
                        labelText: 'Full Name',
                      ),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      controller: _email, // the controller we declared at the top
                      decoration: InputDecoration(
                        labelText: 'Email Address',
                        icon: Icon(Icons.mail),
                      ),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      controller: _phn, // the controller we declared at the top
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        labelText: 'Phone Number',
                        icon: Icon(Icons.call),
                      ),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      controller: _pass,
                      obscureText: hidePass, // the bool we declared earlier 
                      decoration: InputDecoration(
                        labelText: 'Password',
                        icon: Icon(Icons.security),
                        suffixIcon: IconButton(
                          icon: Icon(Icons.visibility),
                          onPressed: () {
                            showandhide(); // we are going to declare a function for showing the password inout call showandhide()
                          },
                        ),
                      ),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      obscureText: hidePass,
                      controller: _cpass,
                      decoration: InputDecoration(
                        labelText: 'Confirm Password',
                        icon: Icon(Icons.border_color),
                        suffixIcon: IconButton(
                          icon: Icon(Icons.visibility),
                          onPressed: () {
                            showandhide();
                          },
                        ),
                      ),
                    ),
                    SizedBox(height: 15),
                    SizedBox(
                      width: 300,
                      child: MaterialButton(
                        onPressed: () {
                          formValidate(
                            name: _name.text,
                            email: _email.text,
                            cpass: _cpass.text,
                            pass: _pass.text,
                            phn: _phn.text,
                          ); // formValidate consist of all of our inputs, so we're just going to declare a function to check they all if the user input is valid or otherwise.
                        },
                        child: Text(
                          'Submit Form',
                          style: TextStyle(color: Colors.white),
                        ),
                        color: Colors.green,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );

Итак, мы должны собрать весь пользовательский ввод и установить его внутри initState, а также избавиться от него.

@override
  void initState() {
    _name = TextEditingController();
    _email = TextEditingController();
    _phn = TextEditingController();
    _pass = TextEditingController();
    _cpass = TextEditingController();
    super.initState();
  }
  @override
  void dispose() {
    _name.dispose();
    _email.dispose();
    _phn.dispose();
    _pass.dispose();
    _cpass.dispose();
    super.dispose();
  }

Показать и скрыть пароль пользователя:

showandhide() {
    setState(() {
      hidePass = !hidePass; 
//this just means if the eye icon is pressed hidepass is not equal to hidepass so true != true i.e false
    });
  }

Итак, после всего этого мы подошли к самой проверке формы:

// here we collect every information we need concerning the input
formValidate({String name, email, phn, pass, cpass}) {
    if (name.toString().isEmpty) {
      _showInSnackBar(message: 'Full name required');
    } else if (!email.toString().contains('@')) {
      _showInSnackBar(message: 'Invalid email address');
    } else if (phn.toString().isEmpty || phn.length != 11) {
      _showInSnackBar(message: 'Invalid phone number');
    } else if (pass.toString().isEmpty || pass.length != 8) {
      _showInSnackBar(message: '8 character required for password');
    } else if (cpass.toString() != pass.toString()) {
      _showInSnackBar(message: 'Password does not match');
    } else {
      openDia(name: name); 
//so after all the input is valid we want to display a little dialog.
    }
  }

Наш штрих-код закусок:

void _showInSnackBar({String message}) {
    _formKey.currentState.showSnackBar(
      SnackBar(
        content: GestureDetector(
          onTap: () {},
          child: Text(
            message,
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
          ),
        ),
        duration: (Duration(seconds: 4)),
        elevation: 0,
        backgroundColor: Colors.black,
      ),
    );
  }

а также код диалога:

openDia({String name}) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Text('$name is now a verified account'),
            title: Text('Registration Successful'),
            actions: <Widget>[
              MaterialButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  'Verified',
                  style: TextStyle(color: Colors.blue),
                ),
              )
            ],
          );
        });
  }

Если мы запустим наше приложение сейчас, у нас должно получиться что-то похожее на это

Полный исходный код преуспеет, если заглянуть в репозиторий:



Поздравляем, вы, наконец, узнали, как проверять вводимые пользователем данные, а также узнали, как улучшить взаимодействие с пользователем, показывая красивое сообщение об ошибке.

Если вам так же понравилась эта статья, как и мне, вы можете поддержать меня, написав 👏 за эту историю, и оставьте комментарий ниже, если у вас есть какие-либо вопросы.

Следуйте за мной в Интернете:
Github, Facebook, Twitter, Instagram, Youtube, Medium, LinkedIn и т. Д. @ Acctgen1

Я новичок в написании статей. Если вы считаете, что мне нужно больше контента, дайте мне знать, оставив комментарий или отправьте мне письмо по электронной почте.