简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM