简体   繁体   中英

Flutter FormBuilder Dropdown validation is not working

Here, I am trying flutter_form_builder for the dropdown. but there is some problem when I check the validation of all fields while button clicks on the Next button. it will check the form state is valid or not. if I click on the next button it will show all the required filed it will show me dropdown also but id I am not the select value from drop-down then it needs do not redirect any other page without selecting dropdown value because there is required validation. so the issue is drop-down validation is showing but not working.

Here is code of my screen :

class _AddWalkinServiceScheduleScreenState
    extends State<AddWalkinServiceScheduleScreen>
    with TickerProviderStateMixin {
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();
  AddWalkinModel model;
  bool autovalidate = false;
  final TextEditingController _bspBusinessLegalAddress =
      TextEditingController();
  LocationResult _pickedLocation;
  Map<String, dynamic> _typeValue;
  AnimationController controller;
  Animation<double> animation;
  final TextEditingController _serviceDate = TextEditingController();
  TextEditingController _serviceTime = new TextEditingController();
  String _isoDate;
  String addresschoice;
  List<String> _imageFilesList2 = [];
  List<File> _licenseImages2 = [];
  bool _isFlexible = false;
  String _serviceType;
  List<dynamic> _type = <dynamic>[];

  @override
  void initState() {
    super.initState();
  }

  Widget _builddate() {
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(left: 11),
            child: Text(
              "Date",
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
          _buildservicedate(),
        ],
      ),
    );
  }


  Widget _buildselectAddress() {
    return Container(
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(left: 11),
            child: Text(
              "Select Address",
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
          ),
          _buildaddresschoice(),
          addresschoice == "Current Location"
              ? _addressTextfield()
              : (addresschoice == "Select from address book" ||
                      model.address != null)
                  ? _addressTextfield()
                  : SizedBox(),
          _buildServicetype()
        ],
      ),
    );
  }

  Widget _addressTextfield() {
    return TudoTextWidget(
      prefixIcon: Icon(FontAwesomeIcons.mapMarkedAlt),
      labelText: "Address",
      hintText: "Address",
      controller: _bspBusinessLegalAddress,
      validator: (val) =>
          Validators.validateRequired(val, "Address"),
    );
  }

  Widget _buildServicetype() {
    return FormBuilder(
      autovalidate: autovalidate,
      child: FormBuilderCustomField(
          attribute: "Select Address",
          validators: [FormBuilderValidators.required()],
          formField: FormField(
            builder: (FormFieldState<dynamic> field) {
              return InputDecorator(
                decoration: InputDecoration(
                  prefixIcon: Icon(Icons.business_center),
                  errorText: field.errorText,
                ),
                isEmpty: _typeValue == [],
                child: new DropdownButtonHideUnderline(
                  child: DropdownButton(
                    hint: Text("Service Type"),
                    isExpanded: true,
                    items: [
                      "Normal",
                      "Urgent",
                      "Emergency",
                    ].map((option) {
                      return DropdownMenuItem(
                        child: Text("$option"),
                        value: option,
                      );
                    }).toList(),
                    value: field.value,
                    onChanged: (value) {
                      field.didChange(value);
                      _serviceType = value;
                    },
                  ),
                ),
              );
            },
          )),
    );
  }



  Widget content(BuildContext context, AddWalkinServiceDetailViewModel awsdVm) {
    var colorStyles = Theming.colorstyle(context);
    Orientation orientation = MediaQuery.of(context).orientation;
    return Scaffold(
      backgroundColor: colorStyles['primary'],
      appBar: AppBar(
        elevation: 0,
        title: Text("Service Details"),
        centerTitle: true,
      ),
    bottomNavigationBar: Container(
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new FlatButton.icon(
              icon: Icon(FontAwesomeIcons.arrowCircleRight),
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
              label: Text('Search'),
              color: colorStyles["primary"],
              textColor: Colors.black,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(7),
              ),
              onPressed: () {
                setState(() {
                  autovalidate = true;
                });
                if (_formkey.currentState.validate()) {
                  List<ServicePicture> id1Images = [];
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => ServiceProviderMapScreen(
                          addWalkinModel: model,
                        ),
                      ),
                    );
                  }
                }
            ),
          ],
        ),
      ),
      body: FadeTransition(
        opacity: animation,
        child: Container(
          child: Form(
            autovalidate: autovalidate,
            key: _formkey,
            child: Stack(
              children: <Widget>[
                SingleChildScrollView(
                  padding: EdgeInsets.all(16.0),
                  child: Container(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        _builddate(),
                        _buildflexible(),

                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new StoreConnector<AppState, AddWalkinServiceDetailViewModel>(
      converter: (Store<AppState> store) =>
          AddWalkinServiceDetailViewModel.fromStore(store),
      builder: (BuildContext context, AddWalkinServiceDetailViewModel awsdVm) =>
          content(context, awsdVm),
    );
  }
}

You should be using FormBuilderDropdown instead. This is included in flutter_form_builder .

DropdownButtonHideUnderline(
  child: FormBuilderDropdown(
    name: 'dropdown'
    hint: Text("Service Type"),
    isExpanded: true,
    items: [
      "Normal",
      "Urgent",
      "Emergency",
    ].map((option) {
      return DropdownMenuItem(
        child: Text("$option"),
        value: option,
      );
    }).toList(),,
  ),
),

Using this, the dropdown value can be extracted by calling it from the Map GlobalKey<FormState>.currentState.value using the name set earlier as the key.

_formKey.currentState.value['dropdown']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM