Learn how to use manage state with getx for flutter radio buttons. Radio buttons and getx state management. You will also learn how to select or toggle the buttons.
Entry point
main.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'button_controller.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
Get.put(ButtonController());
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: SizedBox(
height: 500,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
OrderTypeButton(value: "take_away", title: "Take away", amount: 10, isFree: true),
OrderTypeButton(value: "home_delivery", title: "Home delivery", amount: 10, isFree: false)
],
),
),
)
);
}
}
class OrderTypeButton extends StatelessWidget {
final String value;
final String title;
final double amount;
final bool isFree;
const OrderTypeButton({
required this.value,
required this.title,
required this.amount,
required this.isFree});
@override
Widget build(BuildContext context) {
return GetBuilder<ButtonController>(
builder: (buttonController) {
return InkWell(
onTap: () => buttonController.setOrderType(value),
child: Row(
children: [
Radio(
value: value,
groupValue: buttonController.orderType,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
onChanged: (String? value){
//buttonController.setOrderType(value!);
},
activeColor: Theme.of(context).primaryColor,
),
const SizedBox(width: 10),
Text(title,),
const SizedBox(width: 5),
Text(
'(${(value == 'take_away' || isFree) ? 'free' : amount != -1 ? '\$${amount/10}': 'calculating'})',
),
],
),
);
},
);
}
}
Controller
Below is the controller that maintains the state of the radio buttons
import 'package:get/get.dart';
class ButtonController extends GetxController{
String _orderType = 'home_delivery';
String get orderType =>_orderType;
void setOrderType(String type) {
_orderType = type;
print("The order type is "+_orderType);
update();
}
}