Search code examples
flutterdarttogglebuttonhook-widgets

ToggleButton not changing state


I have three toggle button in my page. When I click either one of the toggle button, it remain unchanged.

class EditInvoiceDetailsScreen extends HookWidget {
  final Invoice invoice;

  EditInvoiceDetailsScreen(this.invoice, {super.key});

  @override
  Widget build(BuildContext context) {
    final isSelected = useState(<bool>[true, false, false]);
    return Scaffold(
      body: _showBody(context, isSelected),
      appBar: AppBar(
          iconTheme: const IconThemeData(color: Colors.white),
          backgroundColor: AppTheme.light.colorScheme.primary,
          title: Text(
            'edit'.tr(),
            style: const TextStyle(color: Colors.white),
          )),
    );
  }
 Widget _showBody(BuildContext context, ValueNotifier<List<bool>> isSelected) {
    return _step2Body(context, isSelected);
  }

  Widget _step2Body(BuildContext context, ValueNotifier<List<bool>> isSelect) {
    return ToggleButtons(
      onPressed: (newIndex) {
        for (int i = 0; i < isSelect.value.length; i++) {
          isSelect.value[i] = i == newIndex;
        }
      },
      // list of booleans
      borderRadius: const BorderRadius.all(Radius.circular(8)),
      selectedBorderColor: Colors.red[700],
      selectedColor: Colors.white,
      fillColor: Colors.red[200],
      color: Colors.red[400],
      constraints: const BoxConstraints(
        minHeight: 40.0,
        minWidth: 80.0,
      ),
      isSelected: isSelect.value,

      // if consistency is needed for all text style
      textStyle: const TextStyle(fontWeight: FontWeight.bold),
      // border properties for each toggle
      renderBorder: true,
      borderColor: Colors.black,
      borderWidth: 1.5,

      children: const [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 12),
          child: Text('MALE', style: TextStyle(fontSize: 18)),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 12),
          child: Text('FEMALE', style: TextStyle(fontSize: 18)),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 12),
          child: Text('OTHER', style: TextStyle(fontSize: 18)),
        ),
      ],
    );
  }

Solution

  • Managed to fix.

    onPressed: (newIndex) {
                for (int i = 0; i < isSelect.value.length; i++) {
                  isSelect.value[i] = i == newIndex;
                  isSelect.value = [...isSelect.value];  // add this line
                }
              },