Enable Disable Raisedbutton Dynamically In Flutter Android

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

RaisedButton widget in flutter has automatically enabling and disabling button functionality without any prop. In flutter we do not pass any function or onClick method to Raised Button then it will automatically disable the button, There is no fix property present for this. So we are using Ternary operator on onPressed event and using the Ternary operator we would enable and disable the button.

Enable Disable Raisedbutton Dynamically In Flutter Android

Complete Code For Enable Disable RaisedButton Dynamically In FLutter:
main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              centerTitle: true,
                backgroundColor: Colors.redAccent,
                title: Text('Enable & Disable Button')
            ),
            body: Center(
                child: Button()
            )
        )
    );
  }
}

class Button extends StatefulWidget {

  ButtonState createState() => ButtonState();

}

class ButtonState extends State<Button> {

  bool isEnabled = true ;

  enableButton(){

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

  disableButton(){

    setState(() {
      isEnabled = false;
    });
  }

  sampleFunction(){

    print('Clicked');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              RaisedButton(
                onPressed: isEnabled ? ()=> sampleFunction() : null,
                color: Colors.green,
                textColor: Colors.white,
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Text('Sample Button'),
              ),
              RaisedButton(
                onPressed: disableButton,
                color: Colors.redAccent,
                textColor: Colors.white,
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Text('Disable Above Button'),
              ),
              RaisedButton(
                onPressed: enableButton,
                color: Colors.redAccent,
                textColor: Colors.white,
                padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                child: Text('Enable Above Button'),
              ),
            ],
          ),
          ),
        );
  }
}

Related Post