在Flutter中,当你从一个有状态的Widget转移到另一个有状态的Widget时,如果你想要保持汉堡图标(通常用于导航抽屉)始终可见,你可以使用PersistentHeaderDelegate
或者AppBar
结合NavigatorObserver
来实现。
适用于需要在多个页面中保持导航图标可见的应用,如电商应用、社交应用等。
以下是一个简单的示例代码,展示如何在Flutter应用中使用AppBar
和NavigatorObserver
来保持汉堡图标始终可见:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () {
_navigatorKey.currentState!.openDrawer();
},
),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Page 1'),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Page1()));
},
),
ListTile(
title: Text('Page 2'),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Page2()));
},
),
],
),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Page1()));
},
child: Text('Go to Page 1'),
),
),
);
}
}
class Page1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page 1'),
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () {
Navigator.of(context).pop();
},
),
),
body: Center(
child: Text('This is Page 1'),
),
);
}
}
class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page 2'),
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: () {
Navigator.of(context).pop();
},
),
),
body: Center(
child: Text('This is Page 2'),
),
);
}
}
通过这种方式,无论用户导航到哪个页面,汉堡图标都会保留在屏幕的左上角。
领取专属 10元无门槛券
手把手带您无忧上云