颤动验证单选按钮

Posted

技术标签:

【中文标题】颤动验证单选按钮【英文标题】:flutter validate radio buttons 【发布时间】:2020-08-05 15:28:55 【问题描述】:

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

【问题讨论】:

【参考方案1】:

您可以在下面复制粘贴运行完整代码 你可以使用包https://pub.dev/packages/flutter_form_builder 支持内置validatorsFormBuilderValidators.required()可以直接使用 你也可以使用custom validator functionhttps://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();
                      ,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  

【讨论】:

以上是关于颤动验证单选按钮的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤动中获得这种单选按钮

颤动单选按钮的问题

颤动中的单选按钮活动颜色不起作用

颤动:自定义单选按钮

颤动 - 如何在颤动中保存状态选择的单选按钮列表?

通过颤动中的单选按钮更改提升的按钮颜色