日历中用于空值的空检查运算符!我正在为分配日历?标记,则发生此null运算符错误,并且当我添加延迟日历LateInitializationError:Field时_calendar@94028380'尚未初始化错误正在获取
class MedicationListChild extends StatefulWidget {
final String? medicationName;
final String? medicationUID;
final String? childUid;
final String? childName;
final Calendar? calendar;
const MedicationListChild({
Key? key,
this.medicationName,
this.medicationUID,
this.childUid,
this.childName,
this.calendar,
}) : super(key: key);
@override
_MedicationListChildState createState() => _MedicationListChildState();
}
class _MedicationListChildState extends State<MedicationListChild> {
Calendar? _calendar;
@override
void initState() => super.initState();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 7.0),
child: Card(
elevation: 3.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(7.0)),
child: InkWell(
splashColor: Colors.blue,
highlightColor: Colors.green,
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CalendarEventPage(_calendar!),
),
);
},
不要使用_calendar
,而是使用widget.calendar
:
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CalendarEventPage(widget.calendar!),
),
);
您没有在_calendar
上分配任何值,因此它保持为null。
与其直接使用!
,不如先进行空检查。
onTap: () {
if(_calendar!=null) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CalendarEventPage(_calendar),
),
);
},
}
如果你只是喜欢访问小部件变量做
onTap: () {
if(widget.calendar!=null) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CalendarEventPage(widget.calendar),
),
);
},
}
尝试以下代码:
class MedicationListChild extends StatefulWidget {
final String? medicationName;
final String? medicationUID;
final String? childUid;
final String? childName;
final Calendar? calendar;
const MedicationListChild({
Key? key,
this.medicationName,
this.medicationUID,
this.childUid,
this.childName,
this.calendar,
}) : super(key: key);
@override
_MedicationListChildState createState() => _MedicationListChildState();
}
class _MedicationListChildState extends State<MedicationListChild> {
@override
void initState() => super.initState();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 7.0),
child: Card(
elevation: 3.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(7.0)),
child: InkWell(
splashColor: Colors.blue,
highlightColor: Colors.green,
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => CalendarEventPage(widget.calendar!),
),
);
},