我正在使用来自 flutter 的表单域小部件 https://pub.dartlang.org/packages/datetime_picker_formfield
但是,我想将用户输入的日期传递回我以前的小部件 (addReminder),但无法做到这一点。
我试过将它放在一个静态变量中并访问它,但没有成功,我对 dart 很弱,所以无法让类具有一个互变量,我可以通过将小部件初始化为一个对象来使用它具有特定变量
并尝试通过 getter 获取变量但失败了。
调用类 dateTime 的父小部件:
class addReminder extends StatelessWidget{
dateTimeWidget = new dateTime();
DateTime date;
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text('Add a Reminder'),
),
body:
new Container(
padding: new EdgeInsets.all(20.0),
child: new Form(
child: new ListView(
children: <Widget>[
new TextFormField(
keyboardType: TextInputType.text, // Use email input type for emails.
decoration: new InputDecoration(
hintText: 'Title of reminder',
),
),
dateTimeWidget,
RaisedButton(
child: Text('Save'),
onPressed:(){
//This is where I want to extract the date and save it to a local variable (date in this case)
Navigator.pop(context);
},
)
],
),
),
),
);
}
将“DateTimePickerFormField”与小部件和状态类一起使用的 DateTime 小部件:
import 'package:flutter/material.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
import 'package:intl/intl.dart';
class dateTime extends StatefulWidget{
@override
dateTimeState createState() => dateTimeState();
}
class dateTimeState extends State<dateTime>{
static DateTime dateT;
InputType inputType = InputType.both;
final formats = {
InputType.both: DateFormat("EEEE, MMMM d, yyyy 'at' h:mma"),
InputType.date: DateFormat('yyyy-MM-dd'),
InputType.time: DateFormat("HH:mm"),
};
Widget build(BuildContext context) => Container(
child: DateTimePickerFormField(
inputType: InputType.both,
editable: true,
format: formats[inputType],
decoration: InputDecoration(
labelText: 'Date/Time', hasFloatingPlaceholder: false),
onChanged: (dt) => setState(() => dateT = dt),
)
);
我后来尝试这样做:
将此方法添加到 addReminder 类:
dateTimee(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context)=> dateTime()),
);
并这样调用它:
dateTimee(context),
并且在我添加的 onchanged 参数中的 dateTime 类中
onChanged: (dt) {
setState(() => dateT = dt);
Navigator.of(context).pop(dateT);
},
但是我得到了错误:
I/flutter (18662): Another exception was thrown:
'package:flutter/src/widgets/navigator.dart': Failed assertion: line1995
pos 12: '!_debugLocked': is not true.
我认为这是因为该方法是 Future 类型,调用应该是对一个小部件 所以我不知道该怎么办 我正在调用的 dateTimee 小部件基于调用小部件 dateTimePickerFromField
最佳答案
看看食谱https://flutter.io/docs/cookbook/navigation/returning-data
总结:Navigator.push
返回一个 future,它将在推送的小部件调用 Navigator.pop
时完成。您可以将返回值传递给 pop
作为 future 解析的值。
// In widget 1..
final result = await Navigator.of(context).push(...);
// In widget 2..
Navigator.of(context).pop('output');
然后一旦 widget 2 调用 pop,widget 1 正在等待的 future 将完成,result
变量将被分配给 'output'
字符串。
关于android-studio - 如何在 flutter 中弹出小部件之前从小部件传递日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54530102/