Conversation


Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


advertisement

How to Validate Forms in Flutter - Form Widget

Flutter Form Widget

Form widget

Form validation and form submission are two things that the form widget helps to implement. For an application to be easy and safe, it is important to check if the information the user provides is valid. If the user happens to fill out the form correctly, the information, the widget displays an error message that is user-friendly to let the users know what exactly happened.

The use of the Form widget with validation in flutter

import 'package:flutter/material.dart';

void main(){
  runApp(MyWidget());
}

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});
  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final _formkey = GlobalKey<FormState>();
  final _name = TextEditingController();
  final _username = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Simple Form Example')),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formkey,
            child: Column(
              children: [
                TextFormField(
                  controller: _name,
                  decoration: InputDecoration(labelText: 'Enter your name'),
                validator: (value){
                  if(value == null || value.isEmpty){
                    return 'Please enter your name';
                  }
                  return null;
                },
                ),

                  TextFormField(
                  controller: _username,
                  decoration: InputDecoration(labelText: 'Enter your username'),
                validator: (value){
                  if(value == null || value.isEmpty){
                    return 'Please enter your username';
                  }
                  return null;
                },
                ),

                SizedBox(height: 20.0,),

                ElevatedButton(
                  onPressed: (){
                    if(_formkey.currentState?.validate() == true){
                      print('form is being submitted');
                    }
                  },
                  child: Text('Submit')
                  )
              ],
            )
            )
        ),
      ),
    );
  }
}


How to Validate Forms in Flutter | Form Widget Tutorial



Flutter Form Form Widget Form widget in flutter flutter form widget flutter form validation flutter form how to validate form flutter form key validation in flutter flutter form fields

advertisement