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?
CodePudding user response:
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;