Flutter 文本未显示我发送给它的变量

Flutter 文本未显示我发送给它的变量,flutter,text,datepicker,messagebox,Flutter,Text,Datepicker,Messagebox,我正在尝试开发一个学习飞镖和颤振的小应用程序。 现在,我有一个带有图标的视图。当我点击这个图标时,我会看到一个带有日期选择器的警报框。 我选择了一个日期,点击OK按钮后,我应该返回到上一个视图。 在第一个视图中,我有一个文本小部件。这个应该显示以前选择的日期。 我的问题是文本小部件没有显示正确的日期。我试图向文本小部件添加一个setState,但出现了一个错误 请参阅下面的代码源代码。 非常感谢 import 'package:flutter/cupertino.dart'; import '

我正在尝试开发一个学习飞镖和颤振的小应用程序。 现在,我有一个带有图标的视图。当我点击这个图标时,我会看到一个带有日期选择器的警报框。 我选择了一个日期,点击OK按钮后,我应该返回到上一个视图。 在第一个视图中,我有一个文本小部件。这个应该显示以前选择的日期。 我的问题是文本小部件没有显示正确的日期。我试图向文本小部件添加一个setState,但出现了一个错误

请参阅下面的代码源代码。 非常感谢


import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'cupertino DatePicker.dart';
import 'package:intl/intl.dart';

var myselectedDate;

class AddProject extends StatefulWidget {

  @override
  _AddProjectState createState() => _AddProjectState();
}

class _AddProjectState extends State<AddProject> {
  final GlobalKey<FormState> _formState = GlobalKey<FormState>();

var gender;

  @override
  Widget build(BuildContext context) {

    String projectName = "";
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Add Project",
        ),
          
          actions: <Widget>[
        Padding(
          padding: EdgeInsets.only(right: 20.0),
            child: GestureDetector(
              onTap: () {},
              child: Icon(
                Icons.save,
                size: 26.0,
              ),
            )
        ),
        ]
    ),
        floatingActionButton: FloatingActionButton(

          child: Icon(
            Icons.send,
            color: Colors.white,
          ),
          onPressed: () {
            //if (_formState.currentState.validate()) {
            //  _formState.currentState.save();

            //  Navigator.pop(context, true);
            }
          //}
            ),
      body: ListView(
        children: <Widget>[
          Form(
            child: Column(
              children: [

                //Field : Type project Name
                Padding(
                  padding: const EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 1.0),
                  child: TextFormField(

                    decoration: InputDecoration(hintText: "Project Name"),
                    maxLength: 200,
                    maxLines: 2,

                    validator: (value) {
                      return value.isEmpty ? "Project name cannot be empty" : null;
                    },
                    onSaved: (value) {
                      projectName = value;
                    },
                  ),
                ),

                //Start Date text
                Container(
                    alignment: Alignment.topLeft,
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(8.0, 18.0, 8.0, 1.0),
                      child: Text("Start Date",style: TextStyle(color: Colors.black87),),
                    )

                ),

                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.fromLTRB(1.0, 5.0, 8.0, 10.0),
                      child: IconButton(
                        splashColor: Colors.lightGreenAccent,
                        icon: Icon(Icons.calendar_today),//Image.asset('assets/icons/tag.png',
                        //height: 30.0, ),

                      //=============================

                        onPressed: () {
                          showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return StatefulBuilder(
                                  builder: (context, setState){
                                    return AlertDialog(
                                      title: Text('Choose Date'),
                                      content: DatePickerDemo(),
                                      actions: <Widget>[
                                        FlatButton(
                                            child: Text("Cancel",
                                                style: TextStyle(
                                                  color: Colors.grey,)),
                                            onPressed: () {
                                              //selectedContext=false;
                                              Navigator.of(context).pop();
                                            },
                                            shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))

                                        ),

                                        FlatButton(
                                          child: Text("OK",
                                              style: TextStyle(
                                                color: Colors.blue,)),
                                          onPressed: () {

                                            myselectedDate=  DateFormat('dd MMMM, yyyy').format(selectedDate);


                                             print  ('test=' + myselectedDate.toString());

                                            Navigator.of(context).pop();
                                          },
                                        ),
                                      ],
                                    );
                                  });
                            },
                          );
                        }

                      //=============================
                    ),),


                    Text('test=' + myselectedDate.toString()),
                  ],

                ),

                    },
                  ),
                ),
              ],
            ),
            key: _formState,
          ),


        ],
      ),
    );
  }


}


进口“包装:颤振/cupertino.dart”;
进口“包装:颤振/材料.省道”;
导入“cupertino DatePicker.dart”;
导入“包:intl/intl.dart”;
Myselectedate变量;
类AddProject扩展StatefulWidget{
@凌驾
_AddProjectState createState()=>\u AddProjectState();
}
类_AddProjectState扩展状态{
最终的GlobalKey _formState=GlobalKey();
变量性别;
@凌驾
小部件构建(构建上下文){
字符串projectName=“”;
返回脚手架(
appBar:appBar(
标题:正文(
“添加项目”,
),
行动:[
填充物(
填充:仅限边缘设置(右侧:20.0),
儿童:手势检测器(
onTap:(){},
子:图标(
图标。保存,
尺寸:26.0,
),
)
),
]
),
浮动操作按钮:浮动操作按钮(
子:图标(
Icons.send,
颜色:颜色,白色,
),
已按下:(){
//if(_formState.currentState.validate()){
//_formState.currentState.save();
//pop(上下文,true);
}
//}
),
正文:ListView(
儿童:[
形式(
子:列(
儿童:[
//字段:键入项目名称
填充物(
填充:LTRB(8.0,8.0,8.0,1.0)中的常量边集,
子项:TextFormField(
装饰:输入装饰(hintText:“项目名称”),
最大长度:200,
maxLines:2,
验证器:(值){
return value.isEmpty?“项目名称不能为空”:null;
},
已保存:(值){
projectName=值;
},
),
),
//开始日期文本
容器(
对齐:alignment.topLeft,
孩子:填充(
填充:从LTRB(8.0,18.0,8.0,1.0)开始的常数边集,
子项:文本(“开始日期”,样式:文本样式(颜色:Colors.black87),),
)
),
划船(
mainAxisAlignment:mainAxisAlignment.start,
儿童:[
填充物(
填充:LTRB(1.0,5.0,8.0,10.0)中的常量边集,
孩子:我的钮扣(
splashColor:Colors.lightGreenAccent,
icon:icon(今天的Icons.calendar_),//Image.asset('assets/Icons/tag.png',
//身高:30.0,),,
//=============================
已按下:(){
显示对话框(
上下文:上下文,
生成器:(BuildContext上下文){
返回状态生成器(
生成器:(上下文,设置状态){
返回警报对话框(
标题:文本(“选择日期”),
内容:DatePickerDemo(),
行动:[
扁平按钮(
子项:文本(“取消”,
样式:TextStyle(
颜色:颜色。灰色,),
已按下:(){
//selectedContext=false;
Navigator.of(context.pop();
},
形状:新圆角矩形边框(边框半径:新边框半径。圆形(30.0))
),
扁平按钮(
子项:文本(“确定”,
样式:TextStyle(
颜色:颜色。蓝色,),
已按下:(){
myselectedDate=DateFormat('dd-MMMM,yyyy')。格式(selectedDate);
打印('test='+myselectedDate.toString());
Navigator.of(context.pop();
},
),
],
);
});
},
);
}
//=============================
),),
Text('test='+myselectedDate.toString()),
],
),
},
),
),
],
),
密钥:_formState,
),
],
),
);
}
}
导入“包装:颤振/材料.省道”;
进口包装:颤振/c
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

import '09_project_add.dart';

//var mySelectedDate = selectedDate;
DateTime selectedDate = DateTime.now();

class DatePickerDemo extends StatefulWidget {
  @override
  _DatePickerDemoState createState() => _DatePickerDemoState();
}

class _DatePickerDemoState extends State<DatePickerDemo> {
  /// Which holds the selected date
  /// Defaults to today's date.


  /// This decides which day will be enabled
  /// This will be called every time while displaying day in calender.
  bool _decideWhichDayToEnable(DateTime day) {
    if ((day.isAfter(DateTime.now().subtract(Duration(days: 1))) &&
        day.isBefore(DateTime.now().add(Duration(days: 10))))) {
      return true;
    }
    return false;
  }

  _selectDate(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    assert(theme.platform != null);
    switch (theme.platform) {
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        return buildMaterialDatePicker(context);
      case TargetPlatform.iOS:
      case TargetPlatform.macOS:
        return buildCupertinoDatePicker(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text(
              "${selectedDate.toLocal()}".split('/')[0],
              style: TextStyle(fontSize: 55, fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: 20.0,
            ),
            RaisedButton(
              onPressed: () => _selectDate(context),
              child: Text(
                'Select date',
                style:
                TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
              ),
              color: Colors.greenAccent,
            ),
          ],
        ),
      ),
    );
  }

  buildCupertinoDatePicker(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext builder) {
          return Container(
            height: MediaQuery.of(context).copyWith().size.height / 3,
            color: Colors.white,
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.date,
              onDateTimeChanged: (picked) {
                if (picked != null && picked != selectedDate)
                  setState(() {
                    selectedDate = picked;
                    myselectedDate = selectedDate;
                  });
              },
              initialDateTime: selectedDate,
              minimumYear: 2020,
              maximumYear: 2125,
            ),
          );
        });
  }

  buildMaterialDatePicker(BuildContext context) async {
    final DateTime picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime(2125),
      initialEntryMode: DatePickerEntryMode.calendar,
      initialDatePickerMode: DatePickerMode.day,
      selectableDayPredicate: _decideWhichDayToEnable,
      helpText: 'Select booking date',
      cancelText: 'Not now',
      confirmText: 'Book',
      errorFormatText: 'Enter valid date',
      errorInvalidText: 'Enter date in valid range',
      fieldLabelText: 'Booking date',
      fieldHintText: 'Date/Month/Year',
      builder: (context, child) {
        return Theme(
          data: ThemeData.light(),
          child: child,
        );
      },
    );
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }
}
    onPressed: () {
      setState(() {
         myselectedDate=  DateFormat('dd MMMM, yyyy').format(selectedDate);
      });

      print('test=' + myselectedDate.toString());
      Navigator.of(context).pop();
    },