
配圖來自網(wǎng)絡(luò),如侵必刪
在Flutter開發(fā)當(dāng)中,我們可能會(huì)遇到以下的需求:
實(shí)現(xiàn)常見的抽屜菜單功能
這個(gè)功能,我們可以使用Scaffold組件的drawer和endDrawer屬性來實(shí)現(xiàn)。這篇博客抽屜菜單的詳細(xì)過程,希望對(duì)看文章的小伙伴有所幫助。
完整的示例代碼
這里直接上完整的示例代碼,感興趣的小伙伴可以復(fù)制到自己的編譯器當(dāng)中修改。
自定義抽屜組件
import 'package:flutter/material.dart';
/// 抽屜View
class DrawerView extends StatelessWidget {
const DrawerView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: const <Widget>[
DrawerHeader(
decoration: BoxDecoration(color: Colors.yellow),
child: Text(
'抽屜菜單的頭部',
style: TextStyle(color: Colors.white, fontSize: 24),
)),
ListTile(
leading: Icon(Icons.message),
title: Text('消息'),
),
ListTile(
leading: Icon(Icons.settings),
title: Text('設(shè)置'),
),
],
),
);
}
}
調(diào)用代碼
import 'package:flutter/material.dart';
import 'package:flutter_one/widget_drawer.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: '抽屜菜單Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
drawer: DrawerView(),
);
}
}
效果如下所示:

image.png
抽屜菜單在很多App都有在使用??瓷狭松厦娴拇a,Flutter的實(shí)現(xiàn)步驟是不是很簡單,自己定義抽屜菜單的界面,然后在主頁面當(dāng)中調(diào)用就可以了。
屬性說明
這里針對(duì)相關(guān)的屬性做出相應(yīng)的屬性說明,熟悉控件的屬性方便大家的使用。
| 屬性名稱 | 屬性說明 |
|---|---|
| drawer | 左邊打開的抽屜菜單 |
| endDrawer | 右邊打開的抽屜菜單 |