How to Disable a Button in Flutter?

We need to make buttons disabled in mobile applications. You created a form to take the user input and a form submit button on mobile application. The button must be disabled user fills all fields of the form.

Syntex

We can use the OutlineButton widget for the take button, the onPressed() method is used to disable that button.

 OutlinedButton(
onPressed: null,
child: Text('Disabled Button'),
)

Let's create an application that contains two buttons: one is enabled and second is disabled using onPressed() method pass null.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio (File >new flutter project)


Step 2: Adding material package


Import method the runApp method in the main function call first while run the application

 import 'package:flutter/material.dart';

 void main() {

     runApp(RunMyApp());

 }

Step 3: Creating a stateless widget

We can create a stateless widget that contains MaterialApp widget,AppBar,etc.

 class RunMyApp extends StatelessWidget {

     const RunMyApp({super.key});  

    @override

    Widget build(BuildContext context) {

    return MaterialApp(home);

     }

 }

Step 4: Creating a Outlined widget

Create the outlined button and give text as a child, when the disabled button while passing NULL to on pressed method.

 OutlinedButton(

     onPressed: null,

     child: Text('Disabled Button'),

 )

Final code : 

 import 'package:flutter/material.dart';

void main()
{
runApp(HomeScreen());
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.green),
home: Scaffold(
appBar: AppBar(
title: Text('Disable Button'),
),
body: Center(
child: Column(
children: [
SizedBox(
height: 250,
),
OutlinedButton(
onPressed: () {},
child: Text('Enabled Button'),
),
SizedBox(
height: 50,
),
OutlinedButton(
onPressed: null,
child: Text('Disabled Button'),
),
],
),
),
),
);
}
}

 

Happy coding!


365Bloggy May 29, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive