How to enable or disable a button on a form?

Issue

In a form, if I want to enable or disable a button based on the content of some textFormFields.
For example, if I have 6 TextFormFields, the button will be activated if only 3 of them have content.

Solution

Here is a sample I have made for you according to your requirement.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Application name
      title: 'Flutter Hello World',
      // Application theme data, you can set the colors for the application as
      // you want
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // A widget which will be started on application startup
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage();

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

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _emailController;
  late TextEditingController _passwordController;

  bool isValid = false;

  @override
  void initState() {
    super.initState();
    _emailController = TextEditingController();
    _passwordController = TextEditingController();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // The title text which will be shown on the action bar
        title: Text("Form"),
      ),
      body: Form(
        key: _formKey,
        onChanged: () {
          setState(() {
            isValid = _formKey.currentState!.validate();
          });
        },
        autovalidateMode: AutovalidateMode.always,
        child: Column(children: [
          TextFormField(
            controller: _emailController,
            decoration: InputDecoration(
              labelText: "Email",
            ),
            validator: (String? value) {
              if (value == null || value.isEmpty) {
                return "email required";
              }
              return null;
            },
          ),
          TextFormField(
              controller: _passwordController,
              decoration: InputDecoration(
                labelText: "Password",
              ),
              validator: (String? value1) {
                if (value1 == null || value1.isEmpty) {
                  return "Password required";
                }
                return null;
              }),
          ElevatedButton(
            onPressed: isValid ? handleSubmit : null,
            child: Text("Login"),
          )
        ]),
      ),
    );
  }

  handleSubmit() {
    debugPrint("pressed");
  }
}

Answered By – Ranjit Shrestha

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.