//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"))
],
)));
}
}
Back to: Flutter index