Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何在颤振中验证表单_Flutter - Fatal编程技术网

Flutter 如何在颤振中验证表单

Flutter 如何在颤振中验证表单,flutter,Flutter,在flatter中提交之前,我正在尝试验证我的字段。但不知何故,它不会验证,因为即使字段为空,验证也总是会实现 这就是我试过的。有人能帮我找出我做错了什么吗 正如您在下面看到的,我甚至设置了验证器和控制器。但即使字段为空,提交也会发生 class _AddNewsState extends State<AddNews> { GlobalKey<FormState> _key = GlobalKey<FormState>(); TextEditingC

flatter
中提交之前,我正在尝试验证我的字段。但不知何故,它不会验证,因为即使字段为空,验证也总是会实现

这就是我试过的。有人能帮我找出我做错了什么吗

正如您在下面看到的,我甚至设置了
验证器
控制器
。但即使字段为空,提交也会发生

class _AddNewsState extends State<AddNews> {
  GlobalKey<FormState> _key = GlobalKey<FormState>();

  TextEditingController _headlineController;
  TextEditingController _descriptionController;
  String _dropDownActivity;

  // get current date
  static var now = new DateTime.now();
  static var formatter = new DateFormat('yyyy-MM-dd');
  String formattedDate = formatter.format(now);

  // get current timie
  dynamic currentTime = DateFormat.jm().format(DateTime.now());

  @override
  void initState() {
    super.initState();
    _headlineController = TextEditingController();
    _descriptionController = TextEditingController();
    _dropDownActivity = "";
  }

  @override
  Widget build(BuildContext context) {
    File _image;
    String image_url = "";

    FileImage _getImage() {
      var img = (File(widget.imgPath));
      setState(() {
        _image = img;
      });
      return FileImage(_image);
    }

    Future _showToastMsg(String msgType, String msg) {
      if (msgType == "success") {
        return Fluttertoast.showToast(
          msg: msg,
          textColor: Colors.white,
          toastLength: Toast.LENGTH_SHORT,
          timeInSecForIosWeb: 1,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.green,
        );
      } else if (msgType == "error") {
        return Fluttertoast.showToast(
          msg: msg,
          textColor: Colors.white,
          toastLength: Toast.LENGTH_SHORT,
          timeInSecForIosWeb: 1,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.red,
        );
      } else {
        return Fluttertoast.showToast(
          msg: msg,
          textColor: Colors.white,
          toastLength: Toast.LENGTH_SHORT,
          timeInSecForIosWeb: 1,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.black,
        );
      }
    }

    get_image_url_from_uploadPicture(String url) {
      image_url = url;
      return image_url;
    }

    showLoadingWhileSaving(BuildContext context) {
      AlertDialog alert = AlertDialog(
        content: new Row(
          children: [
            CircularProgressIndicator(),
            Container(margin: EdgeInsets.only(left: 5), child: Text("Loading")),
          ],
        ),
      );
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) {
          return alert;
        },
      );
    }

    Future _uploadPicture(BuildContext context) async {
      String fileName = basename(_image.path);
      StorageReference storageReference =
          FirebaseStorage.instance.ref().child(fileName);

      StorageUploadTask storageUploadTask = storageReference.putFile(_image);

      showLoadingWhileSaving(context);
      StorageTaskSnapshot storageTaskSnapshot =
          await storageUploadTask.onComplete;

      image_url =
          await (await storageUploadTask.onComplete).ref.getDownloadURL();

      get_image_url_from_uploadPicture(image_url);

      Navigator.pop(context);

      setState(() {
        _showToastMsg("success", "News Successfully Saved!");
      });
    }

    return Scaffold(
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return IconButton(
              icon: const Icon(null),
              color: Colors.white,
              onPressed: () {},
            );
          },
        ),
        centerTitle: true,
        title: Text(
          "Report a News",
        ),
        backgroundColor: Colors.blueGrey,
      ),
      body: Container(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(26.0),
          child: Form(
            key: _key,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Align(
                    alignment: Alignment.center,
                    child: GFImageOverlay(
                      border: Border.all(color: Colors.blueGrey, width: 4.0),
                      height: 200,
                      width: 200,
                      color: Colors.red,
                      shape: BoxShape.circle,
                      boxFit: BoxFit.fill,
                      image: (widget.imgPath != null)
                          ? _getImage()
                          : AssetImage("images/default_news_image.png"),
                    )),
                SizedBox(
                  height: 30.0,
                ),
                TextFormField(
                  textInputAction: TextInputAction.next,
                  controller: _headlineController,
                  validator: (headline) {
                    if (headline == null || headline.isEmpty) {
                      _showToastMsg("error", "Please enter a Headline");
                    }
                  },
                  decoration: InputDecoration(
                    labelText: "Headline",
                    hintText: "Covid-19 new stats",
                    border: OutlineInputBorder(),
                    icon: Icon(Icons.add_box),
                  ),
                ),
                SizedBox(
                  height: 16.0,
                ),
                TextFormField(
                  maxLines: 5,
                  textInputAction: TextInputAction.next,
                  controller: _descriptionController,
                  validator: (description) {
                    if (description == null || description.isEmpty) {
                      _showToastMsg("error", "Please provide a Headline");
                    }
                  },
                  decoration: InputDecoration(
                    labelText: "Description",
                    hintText: "Covid-19 new stats are sky-rock...",
                    border: OutlineInputBorder(),
                    icon: Icon(Icons.message),
                  ),
                ),
                SizedBox(
                  height: 16.0,
                ),
                DropDownFormField(
                  titleText: 'Priority',
                  value: _dropDownActivity,
                  hintText: 'Select the priority',
                  onSaved: (value) {
                    setState(() {
                      _dropDownActivity = value;
                    });
                  },
                  onChanged: (value) {
                    setState(() {
                      _dropDownActivity = value;
                    });
                  },
                  validator: (value) {
                    if (value == null || value == "") {
                      _showToastMsg("error", "Please select a priority");
                    }
                  },
                  dataSource: [
                    {
                      "display": "High",
                      "value": "High",
                    },
                    {
                      "display": "Medium",
                      "value": "Medium",
                    },
                    {
                      "display": "Low",
                      "value": "Low",
                    },
                  ],
                  textField: 'display',
                  valueField: 'value',
                ),
                SizedBox(
                  height: 16.0,
                ),
                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        GFButtonBadge(
                          size: GFSize.SMALL,
                          onPressed: () {
                            _showToastMsg(
                                "other", "Today is : ${formattedDate}");
                          },
                          icon: Icon(
                            Icons.calendar_today,
                            size: 16.0,
                            color: Colors.white,
                          ),
                          text: '',
                        ),
                        SizedBox(
                          width: 10.0,
                        ),
                        Text(
                          "- ${formattedDate}",
                          style: TextStyle(fontSize: 18.0),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 10.0,
                    ),
                    Row(
                      children: <Widget>[
                        GFButtonBadge(
                          size: GFSize.SMALL,
                          onPressed: () {
                            _showToastMsg("other", "Time is : ${currentTime}");
                          },
                          icon: Icon(
                            Icons.alarm,
                            size: 16.0,
                            color: Colors.white,
                          ),
                          text: '',
                        ),
                        SizedBox(
                          width: 10.0,
                        ),
                        Text(
                          "- ${currentTime}",
                          style: TextStyle(fontSize: 18.0),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 14.0,
                    ),
                  ],
                ),
                Align(
                  alignment: Alignment.center,
                  child: Text(
                    "Date and time will be saved automaticallt on \"Save\"",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.grey,
                    ),
                  ),
                ),
                SizedBox(
                  height: 20.0,
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    RaisedButton.icon(
                      icon: Icon(Icons.refresh),
                      color: Colors.orange,
                      textColor: Colors.white,
                      label: Text("Retake"),
                      onPressed: () async {
                        Navigator.of(context).pop();
                      },
                    ),
                    RaisedButton.icon(
                      icon: Icon(Icons.add_a_photo),
                      color: Colors.green,
                      textColor: Colors.white,
                      label: Text("Snap"),
                      onPressed: () async {
                        try {
                          // first upload the photo
                          if (_key.currentState.validate()) {
                            _showToastMsg("other",
                                get_image_url_from_uploadPicture("cool"));
                          } else {
                            _showToastMsg("other",
                                get_image_url_from_uploadPicture("empty"));
                          }

                          // await FireStoreServiceApi().add_news(News(
                          //   headline: _headlineController.text,
                          //   description: _descriptionController.text,
                          //   imageUrl: image_url,
                          //   timeNews: currentTime.toString(),
                          //   timeDate: formattedDate.toString(),
                          //   priority: _dropDownActivity.toString(),
                          // ));
                        } catch (e) {
                          print(e);
                        }
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
class\u addnewstate扩展状态{
GlobalKey _key=GlobalKey();
文本编辑控制器_headlineController;
文本编辑控制器\u描述控制器;
字符串dropDownActivity;
//获取当前日期
static var now=new DateTime.now();
静态变量格式化程序=新的日期格式('yyyy-MM-dd');
String formattedDate=formatter.format(现在);
//获得当前的胆怯
dynamic currentTime=DateFormat.jm().format(DateTime.now());
@凌驾
void initState(){
super.initState();
_headlineController=TextEditingController();
_descriptionController=TextEditingController();
_dropDownActivity=“”;
}
@凌驾
小部件构建(构建上下文){
文件图像;
字符串图像_url=“”;
FileImage\u getImage(){
var img=(文件(widget.imgPath));
设置状态(){
_图像=img;
});
返回FileImage(_image);
}
Future\u showToastMsg(字符串msgType,字符串msg){
如果(msgType==“成功”){
返回Toast.showtoos(
味精:味精,,
textColor:Colors.white,
烤面包片长度:烤面包片长度,
TimeInSecureForiosWeb:1,
重力:ToastGravity.BOTTOM,
背景颜色:Colors.green,
);
}else if(msgType==“error”){
返回Toast.showtoos(
味精:味精,,
textColor:Colors.white,
烤面包片长度:烤面包片长度,
TimeInSecureForiosWeb:1,
重力:ToastGravity.BOTTOM,
背景颜色:Colors.red,
);
}否则{
返回Toast.showtoos(
味精:味精,,
textColor:Colors.white,
烤面包片长度:烤面包片长度,
TimeInSecureForiosWeb:1,
重力:ToastGravity.BOTTOM,
背景颜色:Colors.black,
);
}
}
从上传图片获取图片url(字符串url){
image_url=url;
返回图片地址;
}
保存时显示加载(构建上下文){
AlertDialog alert=AlertDialog(
内容:新行(
儿童:[
CircularProgressIndicator(),
容器(边距:仅限边集(左:5),子项:文本(“装入”),
],
),
);
显示对话框(
禁止:错误,
上下文:上下文,
生成器:(BuildContext上下文){
返回警报;
},
);
}
Future\u uploadPicture(BuildContext上下文)异步{
字符串fileName=basename(_image.path);
StorageReference存储参考=
FirebaseStorage.instance.ref().child(文件名);
StorageUploadTask StorageUploadTask=storageReference.putFile(_image);
保存时显示加载(上下文);
StorageTaskSnapshot StorageTaskSnapshot=
等待storageUploadTask.onComplete;
图片地址=
wait(wait-storageUploadTask.onComplete);
从上传图片(图片url)中获取图片url;
Navigator.pop(上下文);
设置状态(){
_showToastMsg(“成功”,“新闻已成功保存!”);
});
}
返回脚手架(
appBar:appBar(
主角:建筑商(
生成器:(BuildContext上下文){
返回图标按钮(
图标:常量图标(空),
颜色:颜色,白色,
按下:(){},
);
},
),
标题:对,
标题:正文(
“报道新闻”,
),
背景颜色:颜色。蓝灰色,
),
主体:容器(
子:SingleChildScrollView(
填充:常数边集全部(26.0),
孩子:表格(
键:_键,
子:列(
crossAxisAlignment:crossAxisAlignment.start,
mainAxisAlignment:mainAxisAlignment.start,
儿童:[
对齐(
对齐:对齐.center,
儿童:GFImageOverlay(
边框:边框。全部(颜色:颜色。蓝灰色,宽度:4.0),
身高:200,
宽度:200,
颜色:颜色,红色,
形状:BoxShape.circle,
boxFit:boxFit.fill,
图像:(widget.imgPath!=null)
?_getImage()
:AssetImage(“images/default\u news\u image.png”),
)),
大小盒子(
身高:30.0,
),
TextFormField(
textInputAction:textInputAction.next,
控制器:_headlineController,
验证人:(标题){
if(headline==null | | headline.isEmpty){
_showToastMsg(“错误”,“请输入标题”);
}
},
装饰:输入装饰(
标签文字:“标题”,
hintText:“新冠病毒-19新统计数据”,
边框:OutlineInputBorder(),
图标:图标(图标。添加框),
),
),
大小盒子(
身高:16.0,
),
TextFormField(
最大行数:5,
textInputAction:textInputAction.next,
控制器:\描述控制器,
验证器:(说明){
if(description==null | | description.isEmpty){
TextFormField(
  textInputAction: TextInputAction.next,
  controller: _headlineController,
  validator: (headline) {
    if (headline == null || headline.isEmpty) {
      return "Please enter a Headline";
    }
    return null;
  },
  decoration: InputDecoration(
    labelText: "Headline",
    hintText: "Covid-19 new stats",
    border: OutlineInputBorder(),
    icon: Icon(Icons.add_box),
  ),
),