0

我有一个类似主题的问题。这是我的 TextFormField 代码:

class PhoneNumberField extends StatelessWidget {
  final TextEditingController controller;
  final String prefix;

  const PhoneNumberField(
      {Key? key, required this.controller, required this.prefix})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Color(0xfff0eded),
        borderRadius: BorderRadius.circular(15.0),
      ),
      child: Row(
        children: <Widget>[
          Text("  " + prefix + "  ", style: TextStyle(fontSize: 16.0)),
          SizedBox(width: 8.0),
          Expanded(
            child: TextFormField(
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                CustomInputFormatter()
              ],
              controller: controller,
              autofocus: false,
              keyboardType: TextInputType.phone,
              key: Key('EnterPhone-TextFormField'),
              decoration: InputDecoration(
                filled: true,
                fillColor: Colors.transparent,
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(20.0),
                    bottomRight: Radius.circular(20.0),
                  ),
                ),
                errorMaxLines: 1,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class CustomInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    var text = newValue.text;

    if (newValue.selection.baseOffset == 0) {
      return newValue;
    }

    var buffer = new StringBuffer();
    for (int i = 0; i < text.length; i++) {
      buffer.write(text[i]);
      var nonZeroIndex = i + 1;
      if (nonZeroIndex % 3 == 0 && nonZeroIndex != text.length) {
        buffer.write(' ');
      }
    }

    var string = buffer.toString();
    return newValue.copyWith(
        text: string,
        selection: new TextSelection.collapsed(offset: string.length));
  }
}

我想用 ReactiveTextField 替换它以提高验证性能。我需要那个控制器在这里设置 Provider。这就是我所说的那个类:

 Padding(
                    padding:
                        EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
                    child: PhoneNumberField(
                      controller: Provider.of<PhoneAuthDataProvider>(context,
                              listen: false)
                          .phoneNumberController,
                      prefix:
                          countriesProvider.selectedCountry.dialCode ?? "+48",
                    ),
                  ),

将感谢该解决方案,因为在我看来,使用 ReactiveForm 进行验证看起来要好得多:D

4

0 回答 0