0Pricing
Flutter Mobile Development · Leçon

Champs de formulaire personnalisés

Créez des champs de formulaire personnalisés et réutilisables, adaptés aux besoins spécifiques de l’application, pour améliorer sa modularité et l’expérience utilisateur.

Champs de formulaire personnalisés est une leçon Flutter Mobile Development gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Flutter Mobile Development, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Flutter Mobile Development comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Why Custom Form Fields?

When building apps, you often need similar input fields across different screens. Think about email inputs, password fields, or phone numbers.

Copying and pasting the same TextFormField code everywhere can lead to messy, hard-to-maintain code. This is where custom form fields come in!

What is a Custom Field?

A custom form field is essentially a Flutter Widget that wraps other input widgets, like TextFormField, and adds specific styling, validation, or behavior.

  • Reusability: Define it once, use it everywhere.
  • Consistency: Ensures all similar inputs look and behave the same.
  • Clean Code: Reduces boilerplate and improves readability.

Basic Custom Field Structure

Let's start with a simple custom text input field. We'll create a StatelessWidget that wraps a TextFormField. This allows us to define its basic look and feel.

import 'package:flutter/material.dart';

class CustomTextInput extends StatelessWidget {
  final String hintText;

  const CustomTextInput({Key? key, required this.hintText}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        hintText: hintText,
        border: OutlineInputBorder(),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: Text('Custom Field Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: CustomTextInput(hintText: 'Enter your name'),
        ),
      ),
    ),
  ));
}

Adding Controllers & Validation

For our custom field to be truly useful, it needs to accept a TextEditingController to manage its value and a FormFieldValidator for validation. We pass these as parameters to our custom widget.

import 'package:flutter/material.dart';

class CustomValidatedInput extends StatelessWidget {
  final String hintText;
  final TextEditingController controller;
  final String? Function(String?)? validator;

  const CustomValidatedInput({
    Key? key,
    required this.hintText,
    required this.controller,
    this.validator,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
      decoration: InputDecoration(
        hintText: hintText,
        border: OutlineInputBorder(),
      ),
      validator: validator,
    );
  }
}

void main() {
  final TextEditingController _nameController = TextEditingController();
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: Text('Validated Field Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            child: CustomValidatedInput(
              hintText: 'Enter your name (min 3 chars)',
              controller: _nameController,
              validator: (value) {
                if (value == null || value.length < 3) {
                  return 'Name must be at least 3 characters.';
                }
                return null;
              },
            ),
          ),
        ),
      ),
    ),
  ));
}

A Reusable Email Field

Let's create a specific custom field for email input. It will have a predefined keyboard type and a common email validation pattern. This makes it easy to use consistently.

import 'package:flutter/material.dart';

class CustomEmailField extends StatelessWidget {
  final TextEditingController controller;
  final String labelText;

  const CustomEmailField({
    Key? key,
    required this.controller,
    this.labelText = 'Email',
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
      keyboardType: TextInputType.emailAddress,
      decoration: InputDecoration(
        labelText: labelText,
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.email),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please enter your email.';
        }
        if (!RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
            .hasMatch(value)) {
          return 'Please enter a valid email.';
        }
        return null;
      },
    );
  }
}

void main() {
  final TextEditingController _emailController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: Text('Custom Email Field Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                CustomEmailField(controller: _emailController),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      print('Email: ${_emailController.text}');
                    }
                  },
                  child: Text('Submit'),
                ),
              ],
            ),
          ),
        ),
      ),
    ),
  ));
}

Generic Custom Text Input

What if you need a custom field that's flexible enough for various text inputs (names, addresses, etc.) but still offers custom styling? You can pass more properties to make it generic.

import 'package:flutter/material.dart';

class GenericCustomTextField extends StatelessWidget {
  final TextEditingController controller;
  final String labelText;
  final TextInputType keyboardType;
  final bool obscureText;
  final String? Function(String?)? validator;

  const GenericCustomTextField({
    Key? key,
    required this.controller,
    required this.labelText,
    this.keyboardType = TextInputType.text,
    this.obscureText = false,
    this.validator,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
      keyboardType: keyboardType,
      obscureText: obscureText,
      decoration: InputDecoration(
        labelText: labelText,
        border: OutlineInputBorder(),
      ),
      validator: validator,
    );
  }
}

void main() {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: Text('Generic Field Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                GenericCustomTextField(
                  controller: _usernameController,
                  labelText: 'Username',
                  validator: (value) => value!.isEmpty ? 'Enter username' : null,
                ),
                SizedBox(height: 20),
                GenericCustomTextField(
                  controller: _passwordController,
                  labelText: 'Password',
                  obscureText: true,
                  validator: (value) => value!.length < 6 ? 'Min 6 chars' : null,
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      print('Username: ${_usernameController.text}');
                      print('Password: ${_passwordController.text}');
                    }
                  },
                  child: Text('Login'),
                ),
              ],
            ),
          ),
        ),
      ),
    ),
  ));
}

Adding Interactive Elements

Custom fields can also include interactive elements like suffix icons that change state. A common example is a password field with a toggle to show/hide text.

For this, our custom field needs to be StatefulWidget to manage the visibility state.

Custom Password Field with Toggle

Here's how to build a custom password field that allows users to toggle password visibility. Notice the use of StatefulWidget to manage the internal _obscureText state.

import 'package:flutter/material.dart';

class CustomPasswordField extends StatefulWidget {
  final TextEditingController controller;
  final String labelText;

  const CustomPasswordField({
    Key? key,
    required this.controller,
    this.labelText = 'Password',
  }) : super(key: key);

  @override
  _CustomPasswordFieldState createState() => _CustomPasswordFieldState();
}

class _CustomPasswordFieldState extends State<CustomPasswordField> {
  bool _obscureText = true;

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: widget.controller,
      obscureText: _obscureText,
      decoration: InputDecoration(
        labelText: widget.labelText,
        border: OutlineInputBorder(),
        prefixIcon: Icon(Icons.lock),
        suffixIcon: IconButton(
          icon: Icon(
            _obscureText ? Icons.visibility : Icons.visibility_off,
          ),
          onPressed: () {
            setState(() {
              _obscureText = !_obscureText;
            });
          },
        ),
      ),
      validator: (value) {
        if (value == null || value.length < 6) {
          return 'Password must be at least 6 characters.';
        }
        return null;
      },
    );
  }
}

void main() {
  final TextEditingController _passwordController = TextEditingController();
  final _formKey = GlobalKey<FormState>();

  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(title: Text('Password Field Demo')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                CustomPasswordField(controller: _passwordController),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState!.validate()) {
                      print('Password: ${_passwordController.text}');
                    }
                  },
                  child: Text('Submit'),
                ),
              ],
            ),
          ),
        ),
      ),
    ),
  ));
}

Benefits of Custom Fields

Using custom form fields significantly improves your application's development and maintenance:

  • Code DRYness: Don't Repeat Yourself, leading to less code.
  • Easier Updates: Change one custom field, and all instances update automatically.
  • Better UX: Ensures a consistent and intuitive user experience across your app.
  • Simplified Logic: Encapsulates complex validation or UI logic within the field itself.

Quick Check: Custom Fields

Which of the following are primary benefits of creating custom form fields in Flutter?

Recap: Custom Form Fields

You've learned how to create custom form fields in Flutter! By wrapping existing input widgets in your own StatelessWidget or StatefulWidget, you can build reusable, consistent, and maintainable input components.

This approach helps keep your code clean, centralizes design and validation, and drastically improves the user experience by providing a unified interface across your application.

Questions Fréquemment Posées

La leçon « Champs de formulaire personnalisés » est-elle gratuite ?

Oui — le texte complet de « Champs de formulaire personnalisés » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Flutter Mobile Development, passe à CoddyKit PRO. Le cours Flutter Mobile Development comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Champs de formulaire personnalisés » ?

Créez des champs de formulaire personnalisés et réutilisables, adaptés aux besoins spécifiques de l’application, pour améliorer sa modularité et l’expérience utilisateur. Tu pratiques Flutter Mobile Development avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Flutter Mobile Development ?

Aucune expérience préalable n'est requise. Flutter Mobile Development sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « Champs de formulaire personnalisés » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Flutter Mobile Development ?

Oui. Chaque leçon Flutter Mobile Development inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Widget Form et contrôleurs
  2. Techniques de validation des saisies
  3. Champs de formulaire personnalisés
  4. Focus, clavier et expérience de saisie
← Retour à Flutter Mobile Development