【问题标题】:Using Flutter Checkbox() and obtaining initial value from Firestore使用 Flutter Checkbox() 并从 Firestore 获取初始值
【发布时间】:2020-07-05 14:44:51
【问题描述】:

我不是经验丰富的程序员,也找不到任何指导,因此提出了这个问题。我有一个可行的解决方案,但不确定这是否是好的做法。

我在 Form() 中使用小部件 Checkbox()。 TextFormField() 和 DateTimeField() 等小部件有一个名为“initialValue”的参数。 Checkbox() 没有。

对于 TextFormField() 和 DateTimeField() 我通过以下方式获得了 initialValue:

 @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);

    return StreamBuilder<UnitDetails>(
      stream: DatabaseServices(uid: user.userUid, unitUid: widget.unitUid)
          .unitByDocumentID,
      builder: (context, unitDetails) {
        if (!unitDetails.hasData) return Loading();
        return Scaffold(
    etc

Checkbox(value:residentUnit,) 不能在 builder: 中设置其初始值。参数 'value:' 需要在 builder 之前设置为 true 或 false:即在从 Firestore 获取值之前!我解决这个问题的方法是使用 initState()。对 Firestore 的额外调用和针对这一输入小部件的更多代码。

@override
void initState() {
    super.initState();
    Firestore.instance
        .collection("units")
        .document(widget.unitUid)
        .snapshots()
        .listen((snapshot) {
            residentialUnit = snapshot.data['unitResidential'];
        });
}

有没有更好的办法?

【问题讨论】:

    标签: flutter checkbox google-cloud-firestore


    【解决方案1】:

    我认为您可以通过以下答案解决您的问题(使用 FormField)。

    Checkbox form validation

    以下是示例代码。

    FormField(
                initialValue: userProfile.agreement,
                builder: (state) {
                  return Column(
                    children: [
                      Row(
                        children: [
                          Checkbox(
                              activeColor: Colors.blue,
                              value: state.value,
                              onChanged:(value) {
                                setState(() {
                                  state.didChange(value);
                                });
                              }
                            ),
                          Expanded(child: Text('Sample checkbox')),
                        ],
                      ),
                      Text(
                        state.errorText ?? '',
                        style: TextStyle(
                          color: Theme.of(context).errorColor,
                        ),
                      )
                    ],
                  );
                },
                validator: (val) {
                  print('VAL: $val');
                  if (!val) {
                    return 'You need to accept terms';
                  } else {
                    return null;
                  }
                },
              )
    

    【讨论】:

    • 请您提供更多上下文,以防链接中断?谢谢!
    • 我添加了示例代码。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2020-01-04
    • 2020-10-01
    • 2021-10-13
    • 2021-04-17
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    相关资源
    最近更新 更多