profile pic

Precise Asteroid

Welcome to Amir's Blog 👋

Flutter Forms

2022-01-06

I learned the following while building a simple 3 steps

Forms

Import Package

One starts with importing the packed flutter_form_builder

Define key and add the main widget

and defining a key to the form.

The kay should be static and acceable by all the pages

import 'package:flutter_form_builder/flutter_form_builder.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

final GlobalKey<FormBuilderState> fbKey = GlobalKey<FormBuilderState>();


class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return FormBuilder(
        key: fbKey,

Use the built in widgets

Thre are existing widget for most common controls (text, date picker, radios, etc)

FormBuilderTextField(
      initialValue: "",
      obscureText: obscureText,
      name: attribute,
      validator: validator,
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.white,
        border: InputBorder.none,
        hintText: hint,
        hintStyle: const TextStyle(color: Color.fromARGB(255, 188, 180, 172)),
      ),
    );

Validations

One can use standard validations or write custom ones.

attribute: "confirmEmail",
              hint: "ConfirmEmail",
              validator: FormBuilderValidators.compose([
                FormBuilderValidators.required(context),
                FormBuilderValidators.email(context),
                FormBuilderValidators.required(context),
                (val) => val! != fbKey.currentState!.value["Email"]
                    ? 'The values must match'
                    : null,
              ]),

THe validation would run upon validate() or saveAndValidate() calls

if (FormBuilder.of(context)!.saveAndValidate()) {

Made by Amir 💚