Search code examples
flutterflutter-getx

Why do my Radio buttons state not updating?


I've tried :

  • using two Obx, one for each RadioListTile
  • use TextEditingController() as the variable and get the value from gender.text

But the RadioButtons still selecting the initial value/

Minimal code reproduction:

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() => runApp(GetMaterialApp(home: Home()));

class Controller extends GetxController {
  var gender = "F".obs;

  void onChangedGender(String? value) {
    gender = (value ?? "M").obs;
    print(gender.value);
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(context) {
    final Controller c = Get.put(Controller());

    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 400,
          child: Obx(
            () => Row(
              children: [
                Expanded(
                  child: RadioListTile(
                    value: "M",
                    groupValue: c.gender.value,
                    title: const Text("Male"),
                    onChanged: c.onChangedGender,
                  ),
                ),
                Expanded(
                  child: RadioListTile(
                    value: "F",
                    groupValue: c.gender.value,
                    title: const Text("Female"),
                    onChanged: c.onChangedGender,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Try online: https://zapp.run/edit/flutter-zla606cyla70?entry=lib/main.dart&file=lib/main.dart


Solution

  • void onChangedGender(String? value) {
        gender.value = (value ?? "M");
      }
    

    replace your function with the above