3

我正在尝试使用flutter_form_builder以编程方式设置字段的值,但它似乎不在文档中。

控制器:

class LoggedOutNicknameController extends GetxController {
  AnimationController animateController;
  bool formValid;

  final GlobalKey<FormBuilderState> formKey = GlobalKey<FormBuilderState>();

  @override
  void onInit() {}

  @override
  void onReady() {
    final box = GetStorage();
    box.erase();
    if (box.read<dynamic>('nickname') != null &&
        box.read<dynamic>('nickname') != '') {
      print(box.read<dynamic>('nickname')); // prints the value eg 'James'
      final fff = box.read<String>('nickname');
      formKey.currentState.setAttributeValue('nickname', fff);
    }
  }

  @override
  void onClose() {}

  void onFormChange() {
    formValid = formKey.currentState.validate();
  }
}

在该代码设置值之后,该值不会显示在我的文本输入中。

风景:

Expanded(
              flex: 4,
              child: FormBuilder(
                  key: controller.formKey,
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        VpSubtitle1(
                            context,
                            'So nice to meet you! What do your friends call you?',
                            TextAlign.center),
                        FormBuilderTextField(
                          attribute: 'nickname',
                          textAlign: TextAlign.center,
                          decoration:
                              const InputDecoration(hintText: 'Nickname...'),
                          validators: [FormBuilderValidators.required()],
                        )
                      ]))),

为什么值没有显示在文本输入中?

4

1 回答 1

2

在官方文档中非常简单明了,

您可以一次更改一个字段的值,如下所示:

_formKey.currentState.fields['color_picker'].didChange(Colors.black);

或者像这样的多个字段值:

_formKey.currentState.patchValue({
  'age': '50',
  'slider': 6.7,
  'filter_chip': ['Test 1'],
  'choice_chip': 'Test 2',
  'rate': 4,
  'chips_test': [
    Contact('Andrew', 'stock@man.com', 'https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX4057996.jpg'),
  ],
});

请参阅文档中的这一部分: flutter_form_builder:以编程方式更改字段值

于 2021-10-07T21:52:47.203 回答