[英]With flutter/Dart how can I use the BuildContext in an inherited class
我正在經歷一些重構以尋找適合我感受的 flutter 架構/編碼風格。 我喜歡許多小的獨立代碼塊。 因此,例如,我正在嘗試對 AppBar 小部件進行子類化。 我遇到的問題是,在我的子類中,我無法訪問最終頂級小部件的 BuildContext。 在下面的代碼段中,我找不到切換頁面的“導航器”,因為我沒有要傳遞給“of(context)”的上下文。
所以,問題是:當我的后代類需要訪問構建上下文時,我應該使用什么慣用模式來子類化有狀態小部件(例如 AppBar)?
謝謝你的幫助。
import 'package:flutter/material.dart';
class MyBaseAppBar extends AppBar {
MyBaseAppBar( { actions, title }) : super( actions: actions, title: title);
}
class MyPageAppBar extends MyBaseAppBar {
static var myPageActions = <Widget>[
IconButton(
icon: Icon(Icons.view_agenda),
onPressed: () =>Navigator.of( context ). pushNamed("agenda"))
];
MyPageAppBar() : super(
title : Text("My App Bar"),
actions : myPageActions
);
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyPageAppBar(),
body: Container() // for example
);
}
}
在您的情況下,為什么不在 AppBar 構造函數中傳遞上下文? 您還可以在無狀態類中創建一個方法(調用 AppBar 的 class 並將其傳遞給擴展 AppBar 的構造函數。dart 中的函數是第一個 class 對象,因此請記住避免將它們存儲在變量中。作為參數傳遞時。
class MyBaseAppBar extends AppBar {
MyBaseAppBar( { actions, title, @required navigateTo}) : super( actions: actions, title: title);
}
class MyPageAppBar extends MyBaseAppBar {
final var NavigateTo; //you could use the Navigator Object instead for the Datatype
static var myPageActions = <Widget>[
IconButton(
icon: Icon(Icons.view_agenda),
onPressed: () =>Navigator.of( context ). pushNamed("agenda"))
];
MyPageAppBar({@required this.navigateTo}) : super(
title : Text("My App Bar"),
actions : myPageActions
);
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key key}) : super(key: key);
NavigateToFunc( Build context context)
{
// Code to route
}
@override
Widget build(BuildContext context) {
return Scaffold
/// You should be able to access the context in the
MyPageAppBar as it has its own build method
appBar: MyPageAppBar(navigateTo: NavigateToFunc),
body: Container() // for example
);
關於模式,有不少建議的技術來解決您的挑戰。
看看這個https://flutter.dev/docs/development/data-and-backend/state-mgmt/options
我傾向於使用 Provider 插件。 您可以將父小部件包裝在 ChangeNotifierProvider 中,而小部件(子)將在 Consumer 中更改,或者使用 Provider.of.context 在小部件之間傳遞值。 此外,您可能不需要將有狀態小部件與提供程序一起使用。 用消費者包裝改變 state 的小部件
我仍然覺得為了更改頁面而必須添加提供程序和服務是非常蹩腳的,但這似乎是唯一的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.