繁体   English   中英

使用颤振/飞镖如何在继承的 class 中使用 BuildContext

[英]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 的小部件

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

我仍然觉得为了更改页面而必须添加提供程序和服务是非常蹩脚的,但这似乎是唯一的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM