我想让抽屉在所有内容之上时在页面之间进行过渡因此,页面更改和抽屉不会弹出,它必须始终保持在所有的顶部。除非我想隐藏它
使用Redux、Bloc、Provider等状态管理器
为抽屉创建一个单独的小部件,可以在任何需要的地方使用。
示例:用提供者管理抽屉状态
控制器
import 'package:flutter/material.dart';
class MenuController extends ChangeNotifier {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
GlobalKey<ScaffoldState> get scaffoldKey => _scaffoldKey;
void controlMenu() {
if (!_scaffoldKey.currentState!.isDrawerOpen) {
_scaffoldKey.currentState!.openDrawer();
}
}
}
将状态管理添加到小部件树
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.light().copyWith(
scaffoldBackgroundColor: bgColor,
textTheme: GoogleFonts.poppinsTextTheme(Theme.of(context).textTheme)
.apply(bodyColor: Colors.white),
canvasColor: secondaryColor,
),
debugShowCheckedModeBanner: false,
home: MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => MenuController(),
),
],
child: HomeScreen(),
),
);
}
}
创建抽屉小部件
class SideMenu extends StatelessWidget {
const SideMenu({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: [
DrawerHeader(
child: Image.asset("assets/images/logo.png"),
),
DrawerListTile(
title: "Dashboard",
svgSrc: "assets/icons/menu_dashbord.svg",
press: () {},
),
DrawerListTile(
title: "Pages",
svgSrc: "assets/icons/page.svg",
press: () {},
),
DrawerListTile(
title: "Applications",
svgSrc: "assets/icons/application.svg",
press: () {},
),
DrawerListTile(
title: "UI Components",
svgSrc: "assets/icons/ui.svg",
press: () {},
),
DrawerListTile(
title: "Widgets",
svgSrc: "assets/icons/widget.svg",
press: () {},
),
DrawerListTile(
title: "Forms",
svgSrc: "assets/icons/forms.svg",
press: () {},
),
DrawerListTile(
title: "Charts",
svgSrc: "assets/icons/chart.svg",
press: () {},
),
DrawerListTile(
title: "Settings",
svgSrc: "assets/icons/menu_setting.svg",
press: () {},
),
],
),
);
}
}
class DrawerListTile extends StatelessWidget {
const DrawerListTile({
Key? key,
// For selecting those three line once press "Command+D"
required this.title,
required this.svgSrc,
required this.press,
}) : super(key: key);
final String title, svgSrc;
final VoidCallback press;
@override
Widget build(BuildContext context) {
return ListTile(
onTap: press,
horizontalTitleGap: 0.0,
leading: SvgPicture.asset(
svgSrc,
color: primaryColor,
height: 16,
),
title: Text(
title,
style: TextStyle(color: primaryColor),
),
);
}
}
在你的页面中使用抽屉
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<MyAboutPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
key: context.read<MenuController>().scaffoldKey,
appBar: AppBar(
title: Text('About Page'),
),
drawer: SideMenu(),
);
}
}
如果你想打开抽屉,点击控制状态
IconButton(
icon: Icon(Icons.menu),
onPressed: context.read<MenuController>().controlMenu,
),