[英]How to display body under the AppBar of scaffold widget and not below?
[英]Is it possible to pass AppBar from body in Scaffold widget?
我有一个带drawer
的Scaffold
小部件。 我需要在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.