Logo

HƯỚNG NGHIỆP DỮ LIỆU

LẬP TRÌNH FLUTTER

Flutter Form: TextField, Form, Validation đầy đủ

Đăng bởi Admin
Flutter Form: TextField, Form, Validation đầy đủ

Flutter Form: TextField, Form, Validation đầy đủ

Flutter Forms

Form là phần quan trọng trong mọi ứng dụng. Bài viết này sẽ hướng dẫn bạn tạo form hoàn chỉnh với validation trong Flutter.

TextField cơ bản

1. Simple TextField

TextField(
  decoration: InputDecoration(
    labelText: 'Tên',
    border: OutlineInputBorder(),
  ),
)

2. TextField với Controller

final _controller = TextEditingController();

TextField(
  controller: _controller,
  decoration: InputDecoration(
    labelText: 'Email',
    border: OutlineInputBorder(),
  ),
)

// Dispose
@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

Form Widget

1. Form cơ bản

final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: Column(
    children: [
      TextFormField(
        validator: (value) {
          if (value == null || value.isEmpty) {
            return 'Vui lòng nhập tên';
          }
          return null;
        },
      ),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // Form hợp lệ
          }
        },
        child: Text('Submit'),
      ),
    ],
  ),
)

Validation

1. Required Field

TextFormField(
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Trường này là bắt buộc';
    }
    return null;
  },
)

2. Email Validation

TextFormField(
  keyboardType: TextInputType.emailAddress,
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Vui lòng nhập email';
    }
    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
      return 'Email không hợp lệ';
    }
    return null;
  },
)

3. Password Validation

TextFormField(
  obscureText: true,
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'Vui lòng nhập mật khẩu';
    }
    if (value.length < 8) {
      return 'Mật khẩu phải có ít nhất 8 ký tự';
    }
    return null;
  },
)

Complete Form Example

class LoginForm extends StatefulWidget {
  @override
  _LoginFormState createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            controller: _emailController,
            keyboardType: TextInputType.emailAddress,
            decoration: InputDecoration(
              labelText: 'Email',
              prefixIcon: Icon(Icons.email),
              border: OutlineInputBorder(),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Vui lòng nhập email';
              }
              if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                return 'Email không hợp lệ';
              }
              return null;
            },
          ),
          SizedBox(height: 16),
          TextFormField(
            controller: _passwordController,
            obscureText: true,
            decoration: InputDecoration(
              labelText: 'Mật khẩu',
              prefixIcon: Icon(Icons.lock),
              border: OutlineInputBorder(),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Vui lòng nhập mật khẩu';
              }
              if (value.length < 6) {
                return 'Mật khẩu phải có ít nhất 6 ký tự';
              }
              return null;
            },
          ),
          SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                // Handle login
                final email = _emailController.text;
                final password = _passwordController.text;
                print('Email: $email, Password: $password');
              }
            },
            child: Text('Đăng nhập'),
            style: ElevatedButton.styleFrom(
              minimumSize: Size(double.infinity, 50),
            ),
          ),
        ],
      ),
    );
  }
}

Best Practices

1. Dispose Controllers

@override
void dispose() {
  _controller.dispose();
  super.dispose();
}

2. Reusable Validators

class Validators {
  static String? email(String? value) {
    if (value == null || value.isEmpty) {
      return 'Vui lòng nhập email';
    }
    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
      return 'Email không hợp lệ';
    }
    return null;
  }
}

Kết luận

Tạo form với Flutter:

  • TextField: Widget nhập liệu
  • Form: Quản lý form state
  • Validation: Đảm bảo dữ liệu hợp lệ
  • Best Practices: Dispose controllers, reusable validators

Tóm tắt:

  1. TextField: Widget nhập liệu cơ bản
  2. Form: Wrap với Form widget
  3. Validation: Validator functions
  4. Controllers: Quản lý text input

Tạo form chuyên nghiệp sẽ cải thiện user experience! 🚀


Tác giả: Admin
Ngày đăng: 27/02/2025
Chuyên mục: Flutter

Bình luận

Tính năng bình luận đang được phát triển...