To disable a button in Flutter, you can set the onPressed property to null, which will prevent the button from being pressed. To enable the button, you can set the onPressed property to a non-null value.
To dynamically enable or disable a button based on some condition, you can use a StatefulWidget. Here's an example:
import 'package:flutter/material.dart';
class MyButton extends StatefulWidget {
  @override
  _MyButtonState createState() => _MyButtonState();
}
class _MyButtonState extends State<MyButton> {
  bool _isEnabled = true;
  void _toggleEnabled() {
    setState(() {
      _isEnabled = !_isEnabled;
    });
  }
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _isEnabled ? _toggleEnabled : null,
      child: Text('My Button'),
    );
  }
}
In this example, we have a MyButton widget that has a boolean _isEnabled property that determines whether the button is enabled or disabled. The _toggleEnabled method toggles the _isEnabled property, and calls setState to rebuild the widget with the new value.
In the build method, we use the _isEnabled property to conditionally set the onPressed property of the ElevatedButton. If _isEnabled is true, we set the onPressed property to _toggleEnabled, which will enable the button and toggle the _isEnabled property when the button is pressed. If _isEnabled is false, we set the onPressed property to null, which will disable the button.
You can use this MyButton widget in your app like any other widget:
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: MyButton(),
        ),
      ),
    );
  }
}
This example is just one way to enable/disable a button dynamically. There are many other ways to achieve the same result depending on your specific use case.
To know more about Flutter, join our Flutter Course today.