flutter - 清除 flutter 中的文本字段时出现错误 "getter ' 年'被调用为空"

标签 flutter dart flutter-layout flutter-dependencies

这里,当我单击清除按钮时,它不会清除所有文本框,只会清除 expiry_date 字段,并且还会向我显示异常“在 null 上调用 getter Year”。

在此代码中,我有一个清除按钮,当我单击该按钮时,它不会清除该按钮并显示调用 null 的年份。我认为发生这个问题是因为我在 ExpiryDate 小部件中添加了 onChanged 。但我需要一个 onChanged 事件。所以我需要清除一切。希望你能理解这个问题。你的帮助会让我很开心。

这是代码:

 class _BspLicensedSignupPageState extends State<BspLicensedSignupPage>
        with AfterLayoutMixin<BspLicensedSignupPage> {
      final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
      final TextEditingController _bspBusinessLicenseNumber =
          TextEditingController();
      final TextEditingController _bspLicenseAuthorityName =
          TextEditingController();
      final TextEditingController _bspLicenseExpiryDate = TextEditingController();
      final format = new DateFormat.yMMMEd('en-US');
      String _isoDate;

      List<BusinessProfilePicture> _bspLicenseImages =
          new List<BusinessProfilePicture>();
      List<Object> images = List<Object>();

      List<dynamic> _bspLicenseAuthorityTypes = <dynamic>[];
      Map<String, dynamic> _bspLicenseAuthorityType;
      bool _isvisibleissuingauthority = false;

      bool businesslicensecheck = false;
      int radioValue = -1;
      Future<File> licenceimage;
      Future<File> profilepicture;
      DateTime date;
      TimeOfDay time;
      String _countryId;
      BSPSignupRepository _bspSignupRepository = new BSPSignupRepository();
      bool autovalidate = false;
      bool _isEditMode = false;

      int selected = 0;
      List<String> _imageFilesList = [];
      var isUploadingPost = false;
      var isEditInitialised = true;
      List<File> _licenseImages = [];


      @override
      void initState() {
        super.initState();
        _scrollController = ScrollController();
      }

      Widget _buildbusinesslicenseno() {
        return new TudoTextWidget(
          prefixIcon: Icon(FontAwesomeIcons.idCard),
          controller: _bspBusinessLicenseNumber,
          labelText: AppConstantsValue.appConst['licensedsignup']
              ['businesslicenseno']['translation'],
          validator: Validators().validateLicenseno,
        );
      }

      Widget _buildexpirydate() {
        return DateTimeField(
          format: format,
          autocorrect: true,
          autovalidate: false,
          controller: _bspLicenseExpiryDate,
          readOnly: true,
          validator: (date) => (date == null || _bspLicenseExpiryDate.text == '')
              ? 'Please enter valid date'
              : null,
          onChanged: (date) {
            _isoDate = DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
          },
          decoration: InputDecoration(
              labelText: "Expiry Date",
              hintText: "Expiry Date",
              prefixIcon: Icon(
                FontAwesomeIcons.calendar,
                size: 24,
              )),
          onShowPicker: (context, currentValue) {
            return showDatePicker(
              context: context,
              firstDate: DateTime.now(),
              initialDate: currentValue ?? DateTime.now(),
              lastDate: DateTime(2100),
            );
          },
        );
      }

      Widget _buildlicenseauthority() {
        return new TudoTextWidget(
          validator: (val) => Validators.validateName(val, "Issuing Authority"),
          controller: _bspLicenseAuthorityName,
          prefixIcon: Icon(Icons.account_circle),
          labelText: AppConstantsValue.appConst['licensedsignup']
              ['licenseissuingauthority']['translation'],
          hintText: AppConstantsValue.appConst['licensedsignup']
              ['licenseissuingauthority']['translation'],
        );
      }

      Widget _buildlabeluploadlicensepicture() {
        return Text(AppConstantsValue.appConst['licensedsignup']
            ['labeluploadlicenpicture']['translation']);
      }


      Widget _buildlegalbusinesscheck() {
        return TudoConditionWidget(
          text: AppConstantsValue.appConst['licensedsignup']['legalbusinesscheck']
              ['translation'],
        );
      }



      Widget content(
          BuildContext context, BspLicensedSignupViewModel bspLicensedSignupVm) {
        final appBar = AppBar(
          centerTitle: true,
          title: Text("BSP Licensed Details"),
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              NavigationHelper.navigatetoBack(context);
            },
          ),
        );
        final bottomNavigationBar = Container(
          height: 56,
          //margin: EdgeInsets.symmetric(vertical: 24, horizontal: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              new FlatButton.icon(
                icon: Icon(Icons.close),
                label: Text('Clear'),
                color: Colors.redAccent,
                textColor: Colors.black,
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(7),
                ),
                //  onpress
                onPressed: () {
                  _formKey.currentState.reset();
                  _bspBusinessLicenseNumber.clear();
                  _bspLicenseAuthorityName.clear();
                  _bspBusinessLicenseNumber.text = '';
                  _bspLicenseAuthorityName.text = '';

                  setState(() {
                  _licenseImages.clear();
                  _imageFilesList.clear();
                  });
                },
              ),
              new FlatButton.icon(
                icon: Icon(FontAwesomeIcons.arrowCircleRight),
                label: Text('Next'),
                color: colorStyles["primary"],
                textColor: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 30),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(7),
                ),
                onPressed: () async {

                },
              ),
            ],
          ),
        );
        return new Scaffold(
          appBar: appBar,
          bottomNavigationBar: bottomNavigationBar,
          body: Container(
            height: double.infinity,
            width: double.infinity,
            child: Stack(
              children: <Widget>[
                // Background(),
                SingleChildScrollView(
                  controller: _scrollController,
                  child: SafeArea(
                    top: false,
                    bottom: false,
                    child: Form(
                      autovalidate: autovalidate,
                      key: _formKey,
                      child: Scrollbar(
                        child: SingleChildScrollView(
                          dragStartBehavior: DragStartBehavior.down,
                          // padding: const EdgeInsets.symmetric(horizontal: 16.0),
                          child: new Container(
                            margin: EdgeInsets.fromLTRB(30, 30, 30, 0),
                            child: new Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                _buildbusinesslicenseno(),
                                _buildexpirydate(),
                                _buildlegalbusinesscheck()
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }

      @override
      Widget build(BuildContext context) {
        return new StoreConnector<AppState, BspLicensedSignupViewModel>(
          converter: (Store<AppState> store) =>
              BspLicensedSignupViewModel.fromStore(store),
          onInit: (Store<AppState> store) {
            _countryId = store.state.auth.loginUser.user.country.id.toString();
            print('_countryId');
            print(_countryId);
          },
          builder: (BuildContext context,
                  BspLicensedSignupViewModel bspLicensedSignupVm) =>
              content(context, bspLicensedSignupVm),
        );
      }
    }
    }

最佳答案

onChanged 中的格式化程序无法格式化空日期。 因此,您可以在 DateTimeFieldonChanged 方法中添加 null 检查。

像这样:

onChanged: (date) {
           if (date != null){
            _isoDate = DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(date);
           }
          }

关于flutter - 清除 flutter 中的文本字段时出现错误 "getter ' 年'被调用为空",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59026595/

相关文章:

dart - js 包 - 对象的接口(interface)

dart - 是否可以在运行时获取 pubspec.yaml 版本?

user-interface - 使 SliverAppBar 将图像作为背景而不是颜色

flutter - LayoutBuilder 中的 FutureBuilder 多次调用 future

flutter - 如何在 flutter 中仅使一行2个元素中的一个元素居中

firebase - 无法从数据库获取DataSnapshot并获取空值

flutter - 如何从 json 列表中返回对象?

flutter - flutter/dart 中的甘特图

Flutter构建不生成文件

android - 是否在Google Map上使用TextFormField?