Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter Checkbox inside a form with Provider notification is not working

I have a checkbox which is rendered in a form (not defined as FormField as it doesn’t exist native for Flutter and trying to extend that didn’t work anyway):

import 'package:flutter/material.dart';
import 'checkbox_form_field.dart';
import 'package:sellertools/providers/money.dart';
import 'package:provider/provider.dart';


class MoneyFormCheckbox<T extends Money> extends StatelessWidget {
  final String label;

  const MoneyFormCheckbox(this.label, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final initValue = context.read<T>().money == 1;
    return Padding(
        padding: const EdgeInsets.symmetric(vertical: 10),
        child : Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Expanded(
              child:
                  Checkbox(
                   value: initValue,
                   onChanged: (value) => context.read<T>().set(value! ? 1 : 0),
                  )
            )])
    );
  }

}

where the Money class is:

import 'package:flutter/foundation.dart';

class Money with ChangeNotifier {
  double _money = 0;

  double get money => _money;

  void set(double money) {
    _money = money;
    notifyListeners();
  }
}

The problem here is that when I press the checkbox nothing happens, and it stays unchecked. The same behaviour works well with TextFormField classes. Any idea how to make checkbox working too with Provider pattern inside a form?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you should change read to watch to subscribe to the provider:

final initValue = context.read<T>().money == 1;

to

final initValue = context.watch<T>().money == 1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading