側滑菜單在安卓App里面非常常見,比如Gmail,Google Play,Twitter等。看下圖
網上也有很多創建側滑菜單的教程,我也來記錄一下,自己學習創建Drawer的過程。
1. 創建一個空的App
import 'package:flutter/material.dart'; class HomePage extends StatefulWidget{ @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('Hello Flutter'), ), body: new Center( child: new Text('Hello, Flutter!😍😍😍'), ), ); } }
2.添加drawer側滑菜單
給Scaffold添加一個drawer的屬性即可。
@override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('Hello Flutter'), ), drawer: new Drawer(//New added child: new Text('I'm a drawer),//New added ),//New added body: new Center( child: new Text('Hello, Flutter!😍😍😍'), ), ); }
可以看到drawer里面的child,而不是children。說明一個drawer里面,只能存放一個widget。
那剛才的圖片中,Google Play側滑菜單怎么那么多項?
這里我們可以用一個ListView來實現呢,ListView可以包含一個children,我們就可以放很多元素了。
drawer: new Drawer( child: new ListView( children: <Widget>[ new ListTile( title: new Text("識花"), trailing: new Icon(Icons.local_florist), ), new ListTile( title: new Text("搜索"), trailing: new Icon(Icons.search), ), new Divider(), new ListTile( title: new Text("設置"), trailing: new Icon(Icons.settings), ), ], ), ),
每一項通過ListTile相加,分割線用Divider即可。
3.添加點擊事件
前兩部就基本實現了側滑菜單。
但是只是添加了而已,並沒有點擊事件,沒有點擊,就沒法導航到其他頁面。所以我們給ListTile添加onTap事件。
new ListTile( title: new Text("設置"), trailing: new Icon(Icons.settings), onTap: (){ Navigator.of(context).pop(); Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new SettingsPage('Settings Center'))); }, ),
其中,Navigator.of(context).pop();
這句話尤為重要。如果不添加的話,導航進其他的頁面后,再返回來,這個側滑菜單還是傻愣愣的在那兒,並沒有自動關閉。這樣用戶體驗就不好了。
4.點綴
添加和Google Play側滑菜單頂部一樣的用戶頭像。
再ListTile前面添加UserAccountsDrawerHeader即可。
new UserAccountsDrawerHeader( accountName: Text("小薇識花"), accountEmail: Text("flutter@gmail.com"), currentAccountPicture: new GestureDetector( child: new CircleAvatar( backgroundImage: new ExactAssetImage("images/Head0.png"), ), ), decoration: new BoxDecoration( image: new DecorationImage( fit: BoxFit.fill, image: new ExactAssetImage("images/mm.jpg"),),), ),
5.完成