Android 颤振阶跃验证

Android 颤振阶跃验证,android,flutter,stepper,Android,Flutter,Stepper,我无法单独验证步骤。我可以在步进机中验证字段,问题是我想在进入下一步之前验证字段 创建多个表单不是一个好的选择。我试过了,但不实用。有没有办法: 检测当前步骤并仅验证该步骤内的字段 一种逐步验证的简单方法,而不是在提交时 使用列表控制每个步骤的验证 当用户单击“继续”时,执行formKeys[currStep].currentState.validate 您可以复制粘贴运行下面的完整代码 代码片段 List<GlobalKey<FormState>> formKeys =

我无法单独验证步骤。我可以在步进机中验证字段,问题是我想在进入下一步之前验证字段

创建多个表单不是一个好的选择。我试过了,但不实用。有没有办法:

检测当前步骤并仅验证该步骤内的字段 一种逐步验证的简单方法,而不是在提交时 使用列表控制每个步骤的验证 当用户单击“继续”时,执行formKeys[currStep].currentState.validate 您可以复制粘贴运行下面的完整代码 代码片段

List<GlobalKey<FormState>> formKeys = [GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>()];
...
return  Container(
        child:  Form(
          key: _formKey,
          child:  ListView(children: <Widget>[
             Stepper(
              steps: steps,
              type: StepperType.vertical,
              currentStep: this.currStep,
              onStepContinue: () {             
                setState(() {
                  if(formKeys[currStep].currentState.validate()) {
                    if (currStep < steps.length - 1) {
                      currStep = currStep + 1;
                    } else {
                      currStep = 0;
                    }
                  }

                });
              },

...
List<Step> steps = [
     Step(
        title: const Text('Name'),
        //subtitle: const Text('Enter your name'),
        isActive: true,
        //state: StepState.error,
        state: StepState.indexed,
        content: Form(
          key: formKeys[0],
          child: Column(
            children: <Widget>[
               TextFormField(
                focusNode: _focusNode,
                keyboardType: TextInputType.text,
                autocorrect: false,
                onSaved: (String value) {
                  data.name = value;
                },
                maxLines: 1,
                //initialValue: 'Aseem Wangoo',
                validator: (value) {
                  if (value.isEmpty || value.length < 1) {
                    return 'Please enter name';
                  }
                },
                decoration:  InputDecoration(
                    labelText: 'Enter your name',
                    hintText: 'Enter a name',
                    //filled: true,
                    icon: const Icon(Icons.person),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
工作演示

完整代码

import 'package:flutter/material.dart';

void main() {
  runApp( MyApp());
}

List<GlobalKey<FormState>> formKeys = [GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>()];

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return  MyAppScreenMode();
  }
}

class MyData {
  String name = '';
  String phone = '';
  String email = '';
  String age = '';
}

class MyAppScreenMode extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
        theme:  ThemeData(
          primarySwatch: Colors.lightGreen,
        ),
        home:  Scaffold(
          appBar:  AppBar(
            title:  Text('Steppers'),
          ),
          body:  StepperBody(),
        ));
  }
}

class StepperBody extends StatefulWidget {
  @override
  _StepperBodyState createState() =>  _StepperBodyState();
}

class _StepperBodyState extends State<StepperBody> {
  int currStep = 0;
  static var _focusNode =  FocusNode();
  GlobalKey<FormState> _formKey =  GlobalKey<FormState>();
  static MyData data =  MyData();

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {});
      print('Has focus: $_focusNode.hasFocus');
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }



  List<Step> steps = [
     Step(
        title: const Text('Name'),
        //subtitle: const Text('Enter your name'),
        isActive: true,
        //state: StepState.error,
        state: StepState.indexed,
        content: Form(
          key: formKeys[0],
          child: Column(
            children: <Widget>[
               TextFormField(
                focusNode: _focusNode,
                keyboardType: TextInputType.text,
                autocorrect: false,
                onSaved: (String value) {
                  data.name = value;
                },
                maxLines: 1,
                //initialValue: 'Aseem Wangoo',
                validator: (value) {
                  if (value.isEmpty || value.length < 1) {
                    return 'Please enter name';
                  }
                },
                decoration:  InputDecoration(
                    labelText: 'Enter your name',
                    hintText: 'Enter a name',
                    //filled: true,
                    icon: const Icon(Icons.person),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
     Step(
        title: const Text('Phone'),
        //subtitle: const Text('Subtitle'),
        isActive: true,
        //state: StepState.editing,
        state: StepState.indexed,
        content: Form(
          key: formKeys[1],
          child: Column(
            children: <Widget>[
               TextFormField(
                keyboardType: TextInputType.phone,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || value.length < 10) {
                    return 'Please enter valid number';
                  }
                },
                onSaved: (String value) {
                  data.phone = value;
                },
                maxLines: 1,
                decoration:  InputDecoration(
                    labelText: 'Enter your number',
                    hintText: 'Enter a number',
                    icon: const Icon(Icons.phone),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
     Step(
        title: const Text('Email'),
        // subtitle: const Text('Subtitle'),
        isActive: true,
        state: StepState.indexed,
        // state: StepState.disabled,
        content:  Form(
          key: formKeys[2],
          child: Column(
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.emailAddress,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || !value.contains('@')) {
                    return 'Please enter valid email';
                  }
                },
                onSaved: (String value) {
                  data.email = value;
                },
                maxLines: 1,
                decoration:  InputDecoration(
                    labelText: 'Enter your email',
                    hintText: 'Enter a email address',
                    icon: const Icon(Icons.email),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
     Step(
        title: const Text('Age'),
        // subtitle: const Text('Subtitle'),
        isActive: true,
        state: StepState.indexed,
        content:  Form(
          key: formKeys[3],
          child: Column(
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.number,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || value.length > 2) {
                    return 'Please enter valid age';
                  }
                },
                maxLines: 1,
                onSaved: (String value) {
                  data.age = value;
                },
                decoration:  InputDecoration(
                    labelText: 'Enter your age',
                    hintText: 'Enter age',
                    icon: const Icon(Icons.explicit),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
    //  Step(
    //     title: const Text('Fifth Step'),
    //     subtitle: const Text('Subtitle'),
    //     isActive: true,
    //     state: StepState.complete,
    //     content: const Text('Enjoy Step Fifth'))
  ];

  @override
  Widget build(BuildContext context) {
    void showSnackBarMessage(String message,
        [MaterialColor color = Colors.red]) {
      Scaffold
          .of(context)
          .showSnackBar( SnackBar(content:  Text(message)));
    }

    void _submitDetails() {
      final FormState formState = _formKey.currentState;

      if (!formState.validate()) {
        showSnackBarMessage('Please enter correct data');
      } else {
        formState.save();
        print("Name: ${data.name}");
        print("Phone: ${data.phone}");
        print("Email: ${data.email}");
        print("Age: ${data.age}");

        showDialog(
            context: context,
            child:  AlertDialog(
              title:  Text("Details"),
              //content:  Text("Hello World"),
              content:  SingleChildScrollView(
                child:  ListBody(
                  children: <Widget>[
                     Text("Name : " + data.name),
                     Text("Phone : " + data.phone),
                     Text("Email : " + data.email),
                     Text("Age : " + data.age),
                  ],
                ),
              ),
              actions: <Widget>[
                 FlatButton(
                  child:  Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ));
      }
    }

    return  Container(
        child:  ListView(children: <Widget>[
           Stepper(
            steps: steps,
            type: StepperType.vertical,
            currentStep: this.currStep,
            onStepContinue: () {
              setState(() {
                if(formKeys[currStep].currentState.validate()) {
                  if (currStep < steps.length - 1) {
                    currStep = currStep + 1;
                  } else {
                    currStep = 0;
                  }
                }
                // else {
                // Scaffold
                //     .of(context)
                //     .showSnackBar( SnackBar(content:  Text('$currStep')));

                // if (currStep == 1) {
                //   print('First Step');
                //   print('object' + FocusScope.of(context).toStringDeep());
                // }

                // }
              });
            },
            onStepCancel: () {
              setState(() {
                if (currStep > 0) {
                  currStep = currStep - 1;
                } else {
                  currStep = 0;
                }
              });
            },
            onStepTapped: (step) {
              setState(() {
                currStep = step;
              });
            },
          ),
           RaisedButton(
            child:  Text(
              'Save details',
              style:  TextStyle(color: Colors.white),
            ),
            onPressed: _submitDetails,
            color: Colors.blue,
          ),
        ]));
  }
}
使用列表控制每个步骤的验证 当用户单击“继续”时,执行formKeys[currStep].currentState.validate 您可以复制粘贴运行下面的完整代码 代码片段

List<GlobalKey<FormState>> formKeys = [GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>()];
...
return  Container(
        child:  Form(
          key: _formKey,
          child:  ListView(children: <Widget>[
             Stepper(
              steps: steps,
              type: StepperType.vertical,
              currentStep: this.currStep,
              onStepContinue: () {             
                setState(() {
                  if(formKeys[currStep].currentState.validate()) {
                    if (currStep < steps.length - 1) {
                      currStep = currStep + 1;
                    } else {
                      currStep = 0;
                    }
                  }

                });
              },

...
List<Step> steps = [
     Step(
        title: const Text('Name'),
        //subtitle: const Text('Enter your name'),
        isActive: true,
        //state: StepState.error,
        state: StepState.indexed,
        content: Form(
          key: formKeys[0],
          child: Column(
            children: <Widget>[
               TextFormField(
                focusNode: _focusNode,
                keyboardType: TextInputType.text,
                autocorrect: false,
                onSaved: (String value) {
                  data.name = value;
                },
                maxLines: 1,
                //initialValue: 'Aseem Wangoo',
                validator: (value) {
                  if (value.isEmpty || value.length < 1) {
                    return 'Please enter name';
                  }
                },
                decoration:  InputDecoration(
                    labelText: 'Enter your name',
                    hintText: 'Enter a name',
                    //filled: true,
                    icon: const Icon(Icons.person),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
工作演示

完整代码

import 'package:flutter/material.dart';

void main() {
  runApp( MyApp());
}

List<GlobalKey<FormState>> formKeys = [GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>(), GlobalKey<FormState>()];

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return  MyAppScreenMode();
  }
}

class MyData {
  String name = '';
  String phone = '';
  String email = '';
  String age = '';
}

class MyAppScreenMode extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
        theme:  ThemeData(
          primarySwatch: Colors.lightGreen,
        ),
        home:  Scaffold(
          appBar:  AppBar(
            title:  Text('Steppers'),
          ),
          body:  StepperBody(),
        ));
  }
}

class StepperBody extends StatefulWidget {
  @override
  _StepperBodyState createState() =>  _StepperBodyState();
}

class _StepperBodyState extends State<StepperBody> {
  int currStep = 0;
  static var _focusNode =  FocusNode();
  GlobalKey<FormState> _formKey =  GlobalKey<FormState>();
  static MyData data =  MyData();

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {});
      print('Has focus: $_focusNode.hasFocus');
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }



  List<Step> steps = [
     Step(
        title: const Text('Name'),
        //subtitle: const Text('Enter your name'),
        isActive: true,
        //state: StepState.error,
        state: StepState.indexed,
        content: Form(
          key: formKeys[0],
          child: Column(
            children: <Widget>[
               TextFormField(
                focusNode: _focusNode,
                keyboardType: TextInputType.text,
                autocorrect: false,
                onSaved: (String value) {
                  data.name = value;
                },
                maxLines: 1,
                //initialValue: 'Aseem Wangoo',
                validator: (value) {
                  if (value.isEmpty || value.length < 1) {
                    return 'Please enter name';
                  }
                },
                decoration:  InputDecoration(
                    labelText: 'Enter your name',
                    hintText: 'Enter a name',
                    //filled: true,
                    icon: const Icon(Icons.person),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
     Step(
        title: const Text('Phone'),
        //subtitle: const Text('Subtitle'),
        isActive: true,
        //state: StepState.editing,
        state: StepState.indexed,
        content: Form(
          key: formKeys[1],
          child: Column(
            children: <Widget>[
               TextFormField(
                keyboardType: TextInputType.phone,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || value.length < 10) {
                    return 'Please enter valid number';
                  }
                },
                onSaved: (String value) {
                  data.phone = value;
                },
                maxLines: 1,
                decoration:  InputDecoration(
                    labelText: 'Enter your number',
                    hintText: 'Enter a number',
                    icon: const Icon(Icons.phone),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
     Step(
        title: const Text('Email'),
        // subtitle: const Text('Subtitle'),
        isActive: true,
        state: StepState.indexed,
        // state: StepState.disabled,
        content:  Form(
          key: formKeys[2],
          child: Column(
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.emailAddress,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || !value.contains('@')) {
                    return 'Please enter valid email';
                  }
                },
                onSaved: (String value) {
                  data.email = value;
                },
                maxLines: 1,
                decoration:  InputDecoration(
                    labelText: 'Enter your email',
                    hintText: 'Enter a email address',
                    icon: const Icon(Icons.email),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
     Step(
        title: const Text('Age'),
        // subtitle: const Text('Subtitle'),
        isActive: true,
        state: StepState.indexed,
        content:  Form(
          key: formKeys[3],
          child: Column(
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.number,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || value.length > 2) {
                    return 'Please enter valid age';
                  }
                },
                maxLines: 1,
                onSaved: (String value) {
                  data.age = value;
                },
                decoration:  InputDecoration(
                    labelText: 'Enter your age',
                    hintText: 'Enter age',
                    icon: const Icon(Icons.explicit),
                    labelStyle:
                     TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
    //  Step(
    //     title: const Text('Fifth Step'),
    //     subtitle: const Text('Subtitle'),
    //     isActive: true,
    //     state: StepState.complete,
    //     content: const Text('Enjoy Step Fifth'))
  ];

  @override
  Widget build(BuildContext context) {
    void showSnackBarMessage(String message,
        [MaterialColor color = Colors.red]) {
      Scaffold
          .of(context)
          .showSnackBar( SnackBar(content:  Text(message)));
    }

    void _submitDetails() {
      final FormState formState = _formKey.currentState;

      if (!formState.validate()) {
        showSnackBarMessage('Please enter correct data');
      } else {
        formState.save();
        print("Name: ${data.name}");
        print("Phone: ${data.phone}");
        print("Email: ${data.email}");
        print("Age: ${data.age}");

        showDialog(
            context: context,
            child:  AlertDialog(
              title:  Text("Details"),
              //content:  Text("Hello World"),
              content:  SingleChildScrollView(
                child:  ListBody(
                  children: <Widget>[
                     Text("Name : " + data.name),
                     Text("Phone : " + data.phone),
                     Text("Email : " + data.email),
                     Text("Age : " + data.age),
                  ],
                ),
              ),
              actions: <Widget>[
                 FlatButton(
                  child:  Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ));
      }
    }

    return  Container(
        child:  ListView(children: <Widget>[
           Stepper(
            steps: steps,
            type: StepperType.vertical,
            currentStep: this.currStep,
            onStepContinue: () {
              setState(() {
                if(formKeys[currStep].currentState.validate()) {
                  if (currStep < steps.length - 1) {
                    currStep = currStep + 1;
                  } else {
                    currStep = 0;
                  }
                }
                // else {
                // Scaffold
                //     .of(context)
                //     .showSnackBar( SnackBar(content:  Text('$currStep')));

                // if (currStep == 1) {
                //   print('First Step');
                //   print('object' + FocusScope.of(context).toStringDeep());
                // }

                // }
              });
            },
            onStepCancel: () {
              setState(() {
                if (currStep > 0) {
                  currStep = currStep - 1;
                } else {
                  currStep = 0;
                }
              });
            },
            onStepTapped: (step) {
              setState(() {
                currStep = step;
              });
            },
          ),
           RaisedButton(
            child:  Text(
              'Save details',
              style:  TextStyle(color: Colors.white),
            ),
            onPressed: _submitDetails,
            color: Colors.blue,
          ),
        ]));
  }
}

分享你的代码可能会有帮助,否则很难给你一个解决方案。不管我怎么想,分享你的代码可能会有帮助,否则很难给你一个解决方案。不管我怎么想,好吧,我会把它标记为一个答案,但有几件事:我确实在另一个线程中发现了这条评论,这段代码也出现在教程中,但不起作用。我不知道为什么它不工作,然后我意识到外部形式是无用的。您必须执行formKeys[stepIndexHere].currentState.save;每一步,而不仅仅是一步。那么,你能编辑一下你的答案,让它对其他人有帮助吗?谢谢外部已从中移除。谢谢。好吧,我将把它标记为一个答案,但有几件事:我确实在另一个线程中找到了这条评论,在一个教程中也找到了这段代码,但它不起作用。我不知道为什么它不工作,然后我意识到外部形式是无用的。您必须执行formKeys[stepIndexHere].currentState.save;每一步,而不仅仅是一步。那么,你能编辑一下你的答案,让它对其他人有帮助吗?谢谢外部已从中移除。谢谢