![](/img/trans.png)
[英]Flutter [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'BuildContext'
[英]Flutter Error :68:14: Error: Getter not found: 'context'. and Unhandled Exception: type 'Null' is not a subtype of type 'BuildContext'
我不知道那個錯誤是什么意思。但問題是我想在我的 Button 函數中傳入我的 ShowDate Widget 功能,這里是代碼:
class AddTaskPage extends StatefulWidget {
const AddTaskPage({Key? key}) : super(key: key);
@override
_AddTaskPageState createState() => _AddTaskPageState();
}
class _AddTaskPageState extends State<AddTaskPage> {
DateTime _selectedDate = DateTime.now();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: context.theme.backgroundColor,
toolbarHeight: 80,
leading: GestureDetector(
child: Icon(Icons.arrow_back_ios),
onTap: () {
return Get.back();
},
),
),
body: Container(
padding: EdgeInsets.only(left: 20, right: 20),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Add Task",
style: TextStyle(
fontSize: 30,
fontFamily: "Lato",
fontWeight: FontWeight.bold),
),
MyInputField(title: "Title", hint: "Enter Your Title"),
MyInputField(title: "Note", hint: "Enter Your Note"),
MyInputField(
title: "Date",
hint: DateFormat.yMd().format(_selectedDate),
widget: IconButton(
icon: Icon(
Icons.date_range,
color: Colors.red,
),
onPressed: () {
_getDateFromUser();
},
),
),
],
),
),
),
backgroundColor: context.theme.backgroundColor,
);
}
}
_getDateFromUser() async {
DateTime? _pickerDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2015),
lastDate: DateTime(2121),
);
}
底部是上下文屬性出現問題的地方:
_getDateFromUser() async {
DateTime? _pickerDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2015),
lastDate: DateTime(2121),
);
}
當我用 VScode 將鼠標懸停在它上面時,quickfixes 說我需要提供局部變量,然后它可以工作,但是當我單擊圖標按鈕時,它在終端中顯示以下錯誤:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'BuildContext'
如何處理該錯誤? 那什么意識 ?
如果在外部聲明,則必須傳遞上下文。
_getDateFromUser(BuildContext context) async {
DateTime? _pickerDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2015),
lastDate: DateTime(2121),
);
}
``
void pickingdate() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime.now())
.then((pickedDate) {
if (pickedDate == null) {
return;
}
setState(() {
_pickerDate = pickedDate;
});
});
print('...');
}
並調用不帶括號的函數,例如
onPressed: pickingdate,
pickingdate
里面的onPressed
是一個函數引用,基本上就是說它不是立即執行,而是在用戶點擊特定的widget之后執行。(回調)
pickingdate()
是一個函數調用,它會立即執行。
因此,在onPressed
您可以傳遞函數引用或充當回調的匿名函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.