首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查输入值是否包含flutter中给定字符串的值?

如何检查输入值是否包含flutter中给定字符串的值?
EN

Stack Overflow用户
提问于 2021-04-27 17:40:14
回答 1查看 185关注 0票数 0
代码语言:javascript
复制
int X = 0123456789,
_areAlwdCharsTyped = false;

我想检查用户在TextFormField中输入的值是否包含变量X中的任何值。它也需要实时发生。

例如,如果我在TextFormField中输入vV2g,它应该显示X包含textEditingController.text的值。

我尝试使用正则表达式来实现这一点。它工作得很好,除了当我输入一个数字,删除它,然后只输入一些字母时,_areAlwdCharsTyped仍然返回false

代码语言:javascript
复制
int X = 0123456789,

if (myPsWrdController.text.isNotEmpty) 
{
 String allowedChar =
  X;
 final split = textEditingController.text.split('');
 split.forEach((c) {
  if (textEditingController.text.isNotEmpty &&
   allowedChar.contains(c)) {
    _areAlwdCharsTyped = true;
  } else if (textEditingController.text.isEmpty &&
   !allowedChar.contains(c)) {
    _areAlwdCharsTyped = false;
  } else {
    _areAlwdCharsTyped = false;
  }
  });
 } else {
   _areAlwdCharsTyped = false;
 }

我如何使用正则表达式或任何其他方式来实现这一点?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-04-28 13:02:58

代码语言:javascript
复制
RegExp reg = RegExp(r'^[cAzdTnJ574]*$');
//change the characters inside [] to your own !
  String error = '';
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: StatefulBuilder(
            builder: (context, state) {
              return TextField(
                decoration: InputDecoration(
                errorText: error,
                ),
                style: TextStyle(color: Colors.black,),
              onChanged:(str){
                if(str.isEmpty){
                  state((){
                    error = '';
                  });
                }
                else if(!reg.hasMatch(str)){
                  state((){
                    error = 'Input invalid !';
                  });
                }else{
                  state((){
                    error = '';
                  });
                }
              }
              );
            }
          ),
        ),
      ),
    );
  }

我使用StatefulBuilder来显示实时错误!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67280606

复制
相关文章

相似问题

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