我是 Flutter 編程的新手,在導航到新頁面并讓 onPressed 正常作業時遇到問題。我正在使用下面的代碼片段,并且我已經看到其他教程視頻做了同樣的事情,但是當我使用片段時,“(){ Navigator.push(.....); }”中的所有內容都帶有紅色下劃線出現錯誤:
無效的常量值.dart(invalid_constant)
我不知道如何解決這個錯誤,任何幫助將不勝感激,謝謝。
const ListTile(
title: Text('About Me'),
subtitle: Text('Account Information'),
trailing: IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const About()),
);
},
icon: Icon(Icons.keyboard_arrow_right_rounded),
),
),
uj5u.com熱心網友回復:
該錯誤與ListTile onTap 屬性有關。
Widget ListTile 已經定義了 onTap,所以 IconButton 里面的 onPressed 屬性永遠不會被觸發。
嘗試這個:
ListTile(
title: const Text('About Me'),
subtitle: const Text('Account Information'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const About()),
);
},
trailing: const Icon(Icons.keyboard_arrow_right_rounded,),
uj5u.com熱心網友回復:
嘗試洗掉constListTile 附近的關鍵字。如果的建構式About不是const,也將其從push方法中洗掉。
uj5u.com熱心網友回復:
截至目前,dart 函式不支持常量字面量。您正在嘗試使 ListTile 成為常量建構式,但 onPressed 將函式作為引數,該引數不能是常量或最終值。從 ListTile 中洗掉 const 或創建另一個靜態函式,然后將其傳遞給 onPressed。
您可以從以下鏈接查看。
https://github.com/dart-lang/language/issues/1048
您還可以使用 NavigatorState 進行導航。
class MyApp2 extends StatelessWidget {
static final navigatorStateKey = GlobalKey<NavigatorState>();
const MyApp2({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
key: navigatorStateKey,
home: ListView(
children: List.generate(20, (index) =>
const ListTile(
title: Text('About Me'),
subtitle: Text('Account Information'),
trailing: IconButton(
onPressed: onPressed,
icon: Icon(Icons.keyboard_arrow_right_rounded),
),
),
),
),
);
}
static void onPressed() {
MyApp2.navigatorStateKey.currentState.push(
MaterialPageRoute(builder: (context) => const About()));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427314.html
