Flutter 验证单选按钮

i1icjdpr  于 2023-05-19  发布在  Flutter
关注(0)|答案(2)|浏览(157)

如何在用户提交Form后向RadioButton列表中添加验证器函数,以便验证它们(如TextFormFields_formKey.currentState.validate())?

xdnvmnnf

xdnvmnnf1#

你可以复制粘贴下面运行完整的代码
您可以使用包https://pub.dev/packages/flutter_form_builder
它支持内置的validators,例如您可以直接使用的FormBuilderValidators.required()
您也可以使用custom validator function https://pub.dev/packages/flutter_form_builder#custom-validator-function

FormBuilderRadio(
                      decoration:
                          InputDecoration(labelText: 'My chosen language'),
                      attribute: "best_language",
                      leadingInput: true,
                      onChanged: _onChanged,
                      validators: [FormBuilderValidators.required()],
                      options:
                          ["Dart", "Kotlin", "Java", "Swift", "Objective-C"]
                              .map((lang) => FormBuilderFieldOption(
                                    value: lang,
                                    child: Text('$lang'),
                                  ))
                              .toList(growable: false),
                    ),

工作演示

全码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter FormBuilder Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        inputDecorationTheme: InputDecorationTheme(
          labelStyle: TextStyle(color: Colors.purple),
        ),
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  var data;
  bool autoValidate = true;
  bool readOnly = false;
  bool showSegmentedControl = true;
  final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
  final GlobalKey<FormFieldState> _specifyTextFieldKey =
      GlobalKey<FormFieldState>();

  ValueChanged _onChanged = (val) => print(val);
  var genderOptions = ['Male', 'Female', 'Other'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FormBuilder Example"),
      ),
      body: Padding(
        padding: EdgeInsets.all(10),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              FormBuilder(
                // context,
                key: _fbKey,
                autovalidate: true,
                initialValue: {
                  'movie_rating': 5,
                },
                readOnly: false,
                child: Column(
                  children: <Widget>[
                    FormBuilderRadio(
                      decoration:
                          InputDecoration(labelText: 'My chosen language'),
                      attribute: "best_language",
                      leadingInput: true,
                      onChanged: _onChanged,
                      validators: [FormBuilderValidators.required()],
                      options:
                          ["Dart", "Kotlin", "Java", "Swift", "Objective-C"]
                              .map((lang) => FormBuilderFieldOption(
                                    value: lang,
                                    child: Text('$lang'),
                                  ))
                              .toList(growable: false),
                    ),
                  ],
                ),
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: MaterialButton(
                      color: Theme.of(context).accentColor,
                      child: Text(
                        "Submit",
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () {
                        if (_fbKey.currentState.saveAndValidate()) {
                          print(_fbKey.currentState.value);
                        } else {
                          print(_fbKey.currentState.value);
                          print("validation failed");
                        }
                      },
                    ),
                  ),
                  SizedBox(
                    width: 20,
                  ),
                  Expanded(
                    child: MaterialButton(
                      color: Theme.of(context).accentColor,
                      child: Text(
                        "Reset",
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () {
                        _fbKey.currentState.reset();
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
yacmzcpb

yacmzcpb2#

我不想为此使用整个包,但这篇文章帮助我手动解决了这个问题:https://medium.com/free-code-camp/how-to-validate-forms-and-user-input-the-easy-way-using-flutter-e301a1531165
这并不复杂,您基本上只需检查是否选择了一个值:

// I have multiple forms because I am using a stepper
  // so each step form gets its own validation
  bool _validateForm() {
    switch (currentStep) {
      case 0:
        if (userType == null) {
          showRadioError();
          return false;
        }
        break;

      // ... Other cases / steps

    }

    return true;
  }

  // Validate the whole form of the step on button press of "next" button
  void onStepContinue(int stepAmount) {
    bool isLastStep = (currentStep == stepAmount - 1);
    if (isLastStep) {
      //Do something with this information
      print("FINISHED!");
    } else {
      if (_validateForm()) {
        currentStep += 1;
        notifyListeners();
      }
    }
  }

相关问题