【发布时间】:2020-02-29 06:33:40
【问题描述】:
我正在经历一些重构,以寻找适合我感受的 Flutter 架构/编码风格。我喜欢许多小的独立代码块。因此,例如,我正在尝试对 AppBar 小部件进行子类化。我遇到的问题是,在我的子类中,我无法访问最终顶级小部件的 BuildContext。在下面的 sn-p 中,我找不到用于切换页面的“导航器”,因为我没有要传递给“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
);
}
}
【问题讨论】: