我怎樣才能讓它作業?
@override
void dispose() {
timer.cancel();
super.dispose();
}
這就是我所擁有的:
class _ListCell extends State<ListCell> {
@override
void initState() {
super.initState();
Timer timer = Timer.periodic(Duration(seconds: 1), (_) => ListCell());
}
不斷得到錯誤:
Error: The getter 'timer' isn't defined for the class '_ListCell'.
uj5u.com熱心網友回復:
您收到錯誤是因為 timer 變數是在dispose方法的范圍之外定義的。這是因為您在initState方法中定義了變數。
解決方案:
將timer變數的定義移到initState方法之外,如下所示:
class _ListCell extends State<ListCell> {
Timer? timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), (_) => ListCell());
}
...
由于timer變數現在可以為空,因為它是 type Timer?,因此您需要在 dispose 方法中對其使用空檢查運算子。
@override
void dispose() {
timer?.cancel();
super.dispose();
}
結帳 Dart 的詞法范圍
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342543.html
下一篇:如何在顫振中實作滾動條軌道顏色?
