Drawer构造器十分简单:
Drawer({
Key key,
this.elevation = 16.0, // 侧边阴影范围
this.child, //
this.semanticLabel,
})
Flutter提供了UserAccountsDrawerHeader控件可用来作为Drawer的头部,可以更为方便地进行布局,UserAccountsDrawerHeader展示如下:
示例源码:
import 'package:flutter/material.dart';
class DrawerDemo extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return Drawer(
elevation: 16.0,
child: Stack(
children: <Widget>[
Column(
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text('name:xxxx'),
accountEmail: Text('email:[email protected]'),
currentAccountPicture: CircleAvatar(backgroundImage: AssetImage('assets/images/account_picture.jpeg'),),
otherAccountsPictures: <Widget>[
CircleAvatar(backgroundImage: AssetImage('assets/images/account_picture.jpeg')),
CircleAvatar(backgroundImage: AssetImage('assets/images/account_picture.jpeg')),
CircleAvatar(backgroundImage: AssetImage('assets/images/account_picture.jpeg'))
],
arrowColor: Colors.red,
onDetailsPressed: () {
print(1);
},
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'http://pic36.nipic.com/20131203/3822951_102145644000_2.jpg'
),
fit: BoxFit.cover
),
),
),
Expanded(
child: ListView(
padding: EdgeInsets.symmetric(vertical: 10.0),
children: <Widget>[
ListTile(
leading: Icon(Icons.location_on),
title: Text('附近的人'),
),
Divider(),
ListTile(
leading: Icon(Icons.settings),
title: Text('设置'),
),
],
),
),
],
),
Positioned(
bottom: 10,
right: 10,
child: InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.power_settings_new),
),
Text('退出')
],
),
onTap: () => Navigator.pop(context),
)
)
],
)
);
}
}
默认从手机左侧边框向右滑动可呼出左侧边栏,通过Scaffold.of(context).openDrawer()
可以主动呼出左侧边栏,Scaffold.of(context).openEndDrawer()
呼出右侧边栏。
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: OpenDrawer(),
drawer: DrawerDemo(),
endDrawer: DrawerDemo(),
),
);
}
}
class OpenDrawer extends StatelessWidget{
@override
Widget build(BuildContext context) {
// TODO: implement build
return SizedBox.expand(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('呼出左侧侧边栏'),
onPressed: () => Scaffold.of(context).showSnackBar( // 注意此处context不能直接使用MyApp中的context,如果要直接在MyApp中使用此方法,可使用Builder
SnackBar(
content: Text('Have a snack!'),
),
),
),
RaisedButton(
child: Text('呼出右侧侧边栏'),
onPressed: () => Scaffold.of(context).openEndDrawer(),
)
],
),
);
}
}
Builder中使用Scaffold.of(context).openDrawer()
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) => Center(
child: RaisedButton(
child: Text('呼出左侧侧边栏'),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
),
drawer: DrawerDemo(),
endDrawer: DrawerDemo(),
),
);
}
}