首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在验证器外部更新TextFormField的错误

在验证器外部更新TextFormField的错误
EN

Stack Overflow用户
提问于 2020-03-25 10:18:35
回答 3查看 1.3K关注 0票数 2

根据TextFormField文档,在TextFormField下面显示错误的唯一方法是从验证器函数返回一个错误字符串。但是,我有一个文本输入,只有在调用服务器之后才能验证它,并且来自服务器的响应(如果有效)也需要在以后使用。因此,我只在用户按下Submit时执行此操作。但是,如果服务器返回一个无效的响应,我需要更新错误文本,但是因为我在验证器之外,所以我不能这样做。

我说的对吗?有什么方法可以做到这一点吗?

代码语言:javascript
复制
TextFormField(
    autofocus: true,
    onSaved: (String value) => passcode = value,
),
SizedBox(50.0),
RaisedButtton(
    child: Text('SUBMIT'),
    onPressed: () async {
        _formKey.currentState.save();

        dynamic response = await someServerCall();

        if (response.token) {
            // Valid, use token
        } else {
            // INVALID, update error text somehow
        }
    }
)

(这里的所有内容都有不同的父元素,包括列和表单,但这基本上就是我要做的)

EN

回答 3

Stack Overflow用户

发布于 2020-03-27 12:47:09

您可以使用flutter_form_bloc

每个字段都有addError方法,您可以在任何地方调用,在本例中,它将在从服务器接收响应后的onSubmitting方法中。

代码语言:javascript
复制
class MyFormBloc extends FormBloc<String, String> {
  final email = TextFieldBloc();

  MyFormBloc() {
    addFieldBlocs(fieldBlocs: [email]);
  }

  @override
  void onSubmitting() async {
   // Awesome logic...
   username.addError('That email is taken. Try another.');
  }
}

您还可以使用具有去抖动时间的异步验证器。

代码语言:javascript
复制
class MyFormBloc extends FormBloc<String, String> {
  final username = TextFieldBloc(
    asyncValidatorDebounceTime: Duration(milliseconds: 300),
  );

  MyFormBloc() {
    addFieldBlocs(fieldBlocs: [username]);

    username.addAsyncValidators([_checkUsername]);
  }

  Future<String> _checkUsername(String username) async {
    await Future.delayed(Duration(milliseconds: 500));
    if (username.toLowerCase() != 'flutter dev') {
      return 'That username is already taken';
    }
    return null;
  }
}

下面是一个您可以运行的小演示,教程位于form bloc website

pubspec.yaml

代码语言:javascript
复制
dependencies:
  flutter_form_bloc: ^0.11.0

main.dart

代码语言:javascript
复制
import 'package:flutter/material.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  const App({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SubmissionErrorToFieldForm(),
    );
  }
}

class SubmissionErrorToFieldFormBloc extends FormBloc<String, String> {
  final username = TextFieldBloc();

  SubmissionErrorToFieldFormBloc() {
    addFieldBlocs(
      fieldBlocs: [
        username,
      ],
    );
  }

  @override
  void onSubmitting() async {
    print(username.value);

    await Future<void>.delayed(Duration(milliseconds: 500));

    if (username.value.toLowerCase() == 'dev') {
      username.addError(
        'Cached - That username is taken. Try another.',
        isPermanent: true,
      );

      emitFailure(failureResponse: 'Cached error was added to username field.');
    } else {
      username.addError('That username is taken. Try another.');

      emitFailure(failureResponse: 'Error was added to username field.');
    }
  }
}

class SubmissionErrorToFieldForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SubmissionErrorToFieldFormBloc(),
      child: Builder(
        builder: (context) {
          final formBloc =
              BlocProvider.of<SubmissionErrorToFieldFormBloc>(context);

          return Theme(
            data: Theme.of(context).copyWith(
              inputDecorationTheme: InputDecorationTheme(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
              ),
            ),
            child: Scaffold(
              appBar: AppBar(title: Text('Submission Error to Field')),
              body: FormBlocListener<SubmissionErrorToFieldFormBloc, String,
                  String>(
                onSubmitting: (context, state) {
                  LoadingDialog.show(context);
                },
                onSuccess: (context, state) {
                  LoadingDialog.hide(context);

                  Navigator.of(context).pushReplacement(
                      MaterialPageRoute(builder: (_) => SuccessScreen()));
                },
                onFailure: (context, state) {
                  LoadingDialog.hide(context);

                  Scaffold.of(context).showSnackBar(
                      SnackBar(content: Text(state.failureResponse)));
                },
                child: SingleChildScrollView(
                  physics: ClampingScrollPhysics(),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: <Widget>[
                        TextFieldBlocBuilder(
                          textFieldBloc: formBloc.username,
                          keyboardType: TextInputType.multiline,
                          decoration: InputDecoration(
                            labelText: 'Username',
                            prefixIcon: Icon(Icons.sentiment_very_satisfied),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text('"dev" will add a cached error'),
                        ),
                        RaisedButton(
                          onPressed: formBloc.submit,
                          child: Text('SUBMIT'),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

class LoadingDialog extends StatelessWidget {
  static void show(BuildContext context, {Key key}) => showDialog<void>(
        context: context,
        useRootNavigator: false,
        barrierDismissible: false,
        builder: (_) => LoadingDialog(key: key),
      ).then((_) => FocusScope.of(context).requestFocus(FocusNode()));

  static void hide(BuildContext context) => Navigator.pop(context);

  LoadingDialog({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => false,
      child: Center(
        child: Card(
          child: Container(
            width: 80,
            height: 80,
            padding: EdgeInsets.all(12.0),
            child: CircularProgressIndicator(),
          ),
        ),
      ),
    );
  }
}

class SuccessScreen extends StatelessWidget {
  SuccessScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(Icons.tag_faces, size: 100),
            SizedBox(height: 10),
            Text(
              'Success',
              style: TextStyle(fontSize: 54, color: Colors.black),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 10),
            RaisedButton.icon(
              onPressed: () => Navigator.of(context).pushReplacement(
                  MaterialPageRoute(
                      builder: (_) => SubmissionErrorToFieldForm())),
              icon: Icon(Icons.replay),
              label: Text('AGAIN'),
            ),
          ],
        ),
      ),
    );
  }
}
票数 0
EN

Stack Overflow用户

发布于 2021-07-01 00:58:07

添加一个布尔检查,您可以根据服务器调用进行更改

代码语言:javascript
复制
TextFormField(
               validator: (value) {
                   if (hasErrorAfterServerCall)
                          return 'Your Error Message';
                   else
                          return null;
                },
);

服务器调用完成后,您可以再次验证表单

代码语言:javascript
复制
_formKey.currentState!.validate();
票数 0
EN

Stack Overflow用户

发布于 2020-03-25 10:53:18

为什么不在验证器函数中添加服务器调用。在TextFormField中使用验证器,如下所示:

代码语言:javascript
复制
TextFormField( 
                validator: _validateEmail,
                  onSaved: (String value) {
                    email = value;
                  },
                ),


  String _validateEmail(String value) async {
//call to a server inside a validator function
        dynamic response = await someServerCall();
         String  _token="";
        if (response.token) {
            // Valid, use token

           setState((){
       _token = response.token
            });
            return null;
        } else {
            // INVALID, update error text somehow
            return "error";
        }

  }

如果验证器得到null,那么它不会显示任何错误,但如果它获得任何字符串,那么它会将该字符串显示为错误。现在到按钮了

代码语言:javascript
复制
RaisedButtton(
    child: Text('SUBMIT'),
    onPressed: (){
       if (_formKey.currentState.validate()){} _formKey.currentState.save();}
)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60842157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档