Sage-Code Laboratory

Buttons

Flutter tutorial by examples

Key concepts for beginners:
This is an example of toggle button used to enable and disable other buttons.
//toggle button example
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State {
  bool buttonenabled =
      false; //boolean value to track status of enable and disable,
  // false = disable, true = enable

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Enable/Disable Buttons"),
          backgroundColor: Colors.deepOrangeAccent,
        ),
        body: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(20),
            child: Column(
              children: [
                ElevatedButton(
                    onPressed: buttonenabled
                        ? () {
                            //if buttonenabled == true then pass a function otherwise pass "null"
                            print("Elevated Button One pressed");
                          }
                        : null,
                    child: Text("Elevated Button One")),
                OutlinedButton(
                    onPressed: buttonenabled
                        ? () {
                            //if buttonenabled == true then pass a function otherwise pass "null"
                            print("Outline Button Two Pressed");
                          }
                        : null,
                    child: Text("Outline Button Two")),
                ElevatedButton(
                    onPressed: () {
                      setState(() {
                        //setState to refresh UI
                        if (buttonenabled) {
                          buttonenabled = false;
                          //if buttonenabled == true, then make buttonenabled = false
                        } else {
                          buttonenabled = true;
                          //if buttonenabled == false, then make buttonenabled = true
                        }
                      });
                    },
                    child: Text("Toggle Buttons"))
              ],
            )));
  }
}
Responsive image    Responsive image

Back to: Flutter index