繁体   English   中英

是否可以从 Scaffold 小部件中的 body 传递 AppBar?

[英]Is it possible to pass AppBar from body in Scaffold widget?

我有一个带drawerScaffold小部件。 我需要在body显示的屏幕有不同的AppBars (其中一些有PageView指示器,其中一些是单页的,一些有徽标)。 所以我没有将任何AppBar传递给我的Scaffold而是将它包含在我在body使用的小部件中。 但是抽屉和它没有汉堡包图标。

是否可以将此AppBar从我的body小部件传递到包含它的Scaffold

或者,如果有更好的小部件组合方式来解决这种情况,我想尝试一下。

UPD

有一种很好的方式来显示BottomSheet os SnackBar

Scaffold.of(context)
    .showSnackBar(SnackBar(content: Text('Processing Data')));

不幸的是, AppBar并非如此。

似乎您想要一个在切换页面时保持不变的全局Scaffold 在这种情况下,您必须编写自己的逻辑来显示菜单按钮:

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: (context, child) {
        // wrap a scaffold around the Navigator so that it is the same for all pages
        return Scaffold(
          body: AppScaffold(child: child),
          drawer: Drawer(),
        );
      },
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: buildLeadingAction(context),
        title: Text('Home'),
      ),
    );
  }
}

/// Makes it easier to access the outer scaffold with the drawer from any context
class AppScaffold extends InheritedWidget {
  const AppScaffold({Key key, @required Widget child})
      : assert(child != null),
        super(key: key, child: child);

  /// nullable
  static ScaffoldState of(BuildContext context) {
    return context
        .ancestorInheritedElementForWidgetOfExactType(AppScaffold)
        ?.ancestorStateOfType(const TypeMatcher<ScaffoldState>());
  }

  @override
  bool updateShouldNotify(AppScaffold old) => false;
}

/// This is a simple method and not a widget
/// so that null can be returned if no AppScaffold with a drawer was found
Widget buildLeadingAction(BuildContext context) {
  final ScaffoldState appScaffold = AppScaffold.of(context);
  if (appScaffold != null && appScaffold.hasDrawer) {
    return IconButton(
      icon: const Icon(Icons.menu),
      onPressed: () => appScaffold.openDrawer(),
      tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
    );
  } else {
    return null;
  }
}

或者,您也可以将抽屉的Scaffold放置在页面内,并使用GlobalKey访问其ScaffoldState

暂无
暂无

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

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