24.7 C
New York
Friday, October 7, 2022

How to disable a button after pressing it in Flutter

This beginner-friendly article shows you how to disable a button after it has been pressed in Flutter.

Overview

The steps:

1. Create a variable called _isPressed to hold the button condition. In the beginning, _isPressed = false (make sure you’re using a stateful widget).

2. If _isPressed = false, set the button’s onPressed property to a callback function, otherwise, set onPressed to null:

onPressed: _isPressed == false ? _myCallback : null,

3. When the button is pressed, call:

setState(() {
      _isPressed = true;
});

The Complete Example

App preview:

The code:

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

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

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

class _HomePageState extends State<HomePage> {
  // This variable determines whether the button is disable or not
  bool _isPressed = false;

  // This function is called when the button gets pressed
  void _myCallback() {
    setState(() {
      _isPressed = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Kindacode.com'),
        ),
        body: Center(
            child: ElevatedButton(
          onPressed: _isPressed == false ? _myCallback : null,
          child: const Text('I Am A Button'),
        )));
  }
}

That’s it. Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles