使用flutter/Dat,我如何在继承类中使用BuildContext



我正在进行一些重构,以寻找适合我的敏感度的flutter架构/编码风格。我喜欢许多独立的小代码块。因此,我尝试以AppBar小部件为例进行子类化。我遇到的问题是,在我的子类中,我无法访问最终顶层小部件的BuildContext。在下面的代码段中,我找不到用于切换页面的"Navigator",因为我没有要传递到"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并将其传递给扩展AppBar的构造函数的类(中创建一个方法。dart中的函数是第一类对象,所以你可以将它们存储在变量中。当作为参数传递时,请记住避免使用右括号。

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

我喜欢提供商插件。您可以将父窗口小部件包装在ChangeNotificationerProvider中,并将在Consumer中更改的窗口小部件(子窗口小部件(包装起来,或者使用Provider.of.context在窗口小部件之间传递值。此外,您可能不需要将Stateful小部件与provider一起使用。使用Consumer 包装更改状态的小部件

我最终做了这件事。https://medium.com/flutter-community/navigate-without-context-in-flutter-with-a-navigation-service-e6d76e880c1c

我仍然觉得仅仅为了更改页面而添加提供商和服务是非常糟糕的,但遗憾的是,这似乎是唯一的方法。

最新更新