這篇我們來介紹下app上方的導(dǎo)航欄按鈕用法。
我們前面說過scaffold這個腳手架里面有個appBar這個widget。它便是app上面的組件,自然也包含了一些我們需要的按鈕組件,我們來看下示例代碼:
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.menu),
tooltip: 'Navigreation',
onPressed: () => debugPrint('Navigreation button is pressed'),
),
title: Text('導(dǎo)航'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: () => debugPrint('Search button is pressed'),
),
IconButton(
icon: Icon(Icons.more_horiz),
tooltip: 'More',
onPressed: () => debugPrint('More button is pressed'),
)
],
),
body: null);
}
}
- leading
它是頂部導(dǎo)航欄最左邊的按鈕,IconButton便是按鈕組件,里面的icon就是按鈕圖標(biāo),Icons是內(nèi)置的一些圖標(biāo)樣式。tooltip是按鈕說明,onPressed是按鈕事件,我們通過debugPrint可以看到點擊按鈕后,在控制臺輸出對應(yīng)的文字。 - actions
它是頂部導(dǎo)航欄右方的一排組件。 上面代碼我們定義了搜索和...兩個按鈕,分別設(shè)置了其對應(yīng)的按鈕事件。
顯示如下:
button.png
完整代碼如下:
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Home(),
theme: ThemeData(
primarySwatch: Colors.yellow,
),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.menu),
tooltip: 'Navigreation',
onPressed: () => debugPrint('Navigreation button is pressed'),
),
title: Text('導(dǎo)航'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: () => debugPrint('Search button is pressed'),
),
IconButton(
icon: Icon(Icons.more_horiz),
tooltip: 'More',
onPressed: () => debugPrint('More button is pressed'),
)
],
),
body: null);
}
}
