gpt4 book ai didi

flutter - 无法访问Flutter Stateful Widget中的变量

转载 作者:行者123 更新时间:2023-12-03 04:42:59 26 4
gpt4 key购买 nike

我尝试在构造函数的有状态类中使用变量,例如DateTime中。但是我总是收到错误Only static members can be accessed in initializers.。为什么?
代码部分
DateFormat中,我不能使用变量currentDate。还有另一种可能访问此变量吗?

DateTime currentDate;

final _form = GlobalKey<FormState>();
final _dateTimeController = TextEditingController(
text: DateFormat("HH:mm")
.format(DateTime(currentDate.year, currentDate.month, currentDate.day,
TimeOfDay.now().hour, TimeOfDay.now().minute))
.toString(),
);

var _editedCalendarEntry = CalendarEntry(
dateTime: DateTime.now(),
meetingPlace: "",
minutes: 0,
servicePartner: "",
status: "inactive",
timestamp: Timestamp.now());

@override
void initState() {
currentDate = widget.currentDate;
super.initState();
}
整个类
class AddCalendarEntry extends StatefulWidget {
final ScrollController scrollController;
final DateTime currentDate;

AddCalendarEntry({this.scrollController, this.currentDate});

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

class _AddCalendarEntryState extends State<AddCalendarEntry> {
DateTime currentDate;

final _form = GlobalKey<FormState>();
final _dateTimeController = TextEditingController(
text: DateFormat("HH:mm")
.format(DateTime(currentDate.year, currentDate.month, currentDate.day,
TimeOfDay.now().hour, TimeOfDay.now().minute))
.toString(),
);

var _editedCalendarEntry = CalendarEntry(
dateTime: DateTime.now(),
meetingPlace: "",
minutes: 0,
servicePartner: "",
status: "inactive",
timestamp: Timestamp.now());

@override
void initState() {
currentDate = widget.currentDate;
super.initState();
}

@override
void dispose() {
_dateTimeController.dispose();
super.dispose();
}

Future<Null> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: widget.currentDate,
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101),
);
if (picked != null && picked != currentDate)
setState(() {
currentDate = picked;
print("Erfolgreich");
});
_editedCalendarEntry = CalendarEntry(
servicePartner: _editedCalendarEntry.servicePartner,
dateTime: DateTime(
picked.year,
picked.month,
picked.day,
_editedCalendarEntry.dateTime.hour,
_editedCalendarEntry.dateTime.minute),
meetingPlace: _editedCalendarEntry.meetingPlace,
minutes: _editedCalendarEntry.minutes,
status: _editedCalendarEntry.status);
}

void onTimeValueChanged(TimeOfDay time) {
HapticFeedback.lightImpact();

_editedCalendarEntry = CalendarEntry(
servicePartner: _editedCalendarEntry.servicePartner,
dateTime: DateTime(
_editedCalendarEntry.dateTime.year,
_editedCalendarEntry.dateTime.month,
_editedCalendarEntry.dateTime.day,
time.hour,
time.minute),
meetingPlace: _editedCalendarEntry.meetingPlace,
minutes: _editedCalendarEntry.minutes,
status: _editedCalendarEntry.status);

setState(() {
currentDate = _editedCalendarEntry.dateTime;
});
}

Future<Null> _selectTime(BuildContext context) async {
Navigator.of(context).push(
showPicker(
context: context,
value: TimeOfDay(hour: 9, minute: 0),
onChange: (time) => onTimeValueChanged(time),
is24HrFormat: true,
blurredBackground: false,
accentColor: Theme.of(context).primaryColor),
);
}

void _saveForm() {
_form.currentState.save();
print(_editedCalendarEntry.dateTime);
}

@override
Widget build(BuildContext context) {
return Material(
color: Theme.of(context).bottomSheetTheme.backgroundColor,
child: CupertinoPageScaffold(
backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
child: CustomScrollView(
controller: widget.scrollController,
physics: ClampingScrollPhysics(),
slivers: <Widget>[
CupertinoSliverNavigationBar(
backgroundColor:
Theme.of(context).bottomSheetTheme.backgroundColor,
automaticallyImplyLeading: false,
largeTitle: Text("Neuer Eintrag"),
border: Border.fromBorderSide(
BorderSide(color: Colors.transparent))),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
child: Form(
key: _form,
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Container(width: 100, child: Text("Partner")),
Expanded(
child: TextFormField(
strutStyle: StrutStyle.disabled,
style: TextStyle(
color: Theme.of(context).primaryColor),
decoration: const InputDecoration(
border: InputBorder.none),
onSaved: (value) => {
_editedCalendarEntry = CalendarEntry(
servicePartner: value,
dateTime: _editedCalendarEntry.dateTime,
meetingPlace:
_editedCalendarEntry.meetingPlace,
minutes: _editedCalendarEntry.minutes,
status: _editedCalendarEntry.status)
},
),
),
],
),
Divider(
height: 0,
),
Row(
children: <Widget>[
Container(width: 100, child: Text("Datum")),
Expanded(
child: TextFormField(
initialValue: DateFormat('dd.MM.yyyy')
.format(currentDate)
.toString(),
strutStyle: StrutStyle.disabled,
readOnly: true,
style: TextStyle(
color: Theme.of(context).primaryColor),
decoration: const InputDecoration(
hintText: 'Datum',
border: InputBorder.none,
),
),
),
CupertinoButton(
onPressed: () => _selectDate(context),
child: Text('Auswählen'),
),
],
),
Divider(
height: 0,
),
Row(
children: <Widget>[
Container(width: 100, child: Text("Uhrzeit")),
Expanded(
child: TextFormField(
controller: _dateTimeController,
strutStyle: StrutStyle.disabled,
style: TextStyle(
color: Theme.of(context).primaryColor),
decoration: const InputDecoration(
hintText: 'Uhrzeit',
border: InputBorder.none),
),
),
CupertinoButton(
onPressed: () => _selectTime(context),
child: Text('Auswählen'),
),
],
),
CupertinoButton.filled(
child: Text("Speichern"), onPressed: _saveForm)
],
)),
),
),
)
],
),
),
);
}
}
谢谢你的帮助!

最佳答案

final _form = GlobalKey<FormState>();

// also TextEditingController data type should be initialized
// In your code, I cannot see that
final TextEditinController _dateTimeController = ...
...是一个初始化程序,目前无法访问它。初始化程序在构造函数之前执行,但是只允许在对 super 构造函数的调用(在您的示例中是隐含的)完成后才能访问初始化程序。因此,仅在构造函数主体(或更高版本)中允许对此进行访问。
这就是为什么您收到错误消息的原因:
DateTime(currentDate.year, currentDate.month, currentDate.day, TimeOfDay.now().hour, TimeOfDay.now().minute)
访问 _dateTimeController(如果您未明确编写,则为隐式)。
您可以做的是,在初始化 _dateTimeController之后,在 initState()中初始化 currentDate
DateTime currentDate;

final _form = GlobalKey<FormState>();
final TextEditingController _dateTimeController;

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

currentDate = widget.currentDate;

// here you do that to prevent that error
_dateTimeController = TextEditingController(
text: DateFormat("HH:mm")
.format(DateTime(currentDate.year, currentDate.month, currentDate.day,
TimeOfDay.now().hour, TimeOfDay.now().minute))
.toString(),
);
}
希望这能消除您的疑问,并在很大程度上为您提供帮助。

关于flutter - 无法访问Flutter Stateful Widget中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62834957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com