我把Scaffold的appBar宣告為一個超范圍的變數。
PreferredSizeWidget originAppBar = AppBar(
centerTitle: true,
backgroundColor: Colors.white,
title: ....
這使得我可以通過將originAppBar分配給appBar:來使用它。
appBar: originAppBar,
然而,我在originAppBar中包含了以下代碼。
Navigator.of(context).pushNamed(Profile.route)。
這是一個需要BuildContext的函式,并且不在originAppBar中。
是否可以有一個帶引數的PreferredSizeWidget?像這樣的C#;
/C#
PreferredSizeWidget originAppBar = new PreferredSizeWidget(BuildContext context)
Widget build(BuildContext xontext){
....
appBar: originAppBar(context)
....
}
謝謝你。
uj5u.com熱心網友回復:
使用GlobalKey - 將其分配給你的部件
全域鍵可以唯一地識別元素。全域鍵提供了對與這些元素相關的其他物件的訪問,例如BuildContext。
https://api.flutter.dev/flutter/widgets/GlobalKey-class.html
uj5u.com熱心網友回復:
看來這個定義是錯誤的。
以下是正確的。
PreferredSizeWidget originAppBar(BuildContext context) {
return AppBar(....)
}
....
Widget build(BuildContext context) {
return Scaffold(
appBar: originAppBar(context),
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/313099.html
標籤:
