Flutterで初心者が知りたかったWidgetのまとめ
最近、Flutterの勉強を始めたので、備忘録がてらWidgetの基礎的なことをまとめていく。
Widgetとは?
Widgetとは、UIの部品のことを指す。
例えば、ListView
やText
などの様々なWidgetが用意されており、
それらを組み合わせることでアプリを作っていく。
もちろん、独自のWidgetを作ることもできる。
よく使うWidgetのまとめ。
以下は、よく使うWidgetをまとめる。
Scafford
Scaffoldは、アプリ画面の「骨組み」を提供するウィジェット。 アプリでメインで表示したい画面だけでなく、ヘッダーやサイドメニューなども定義できる。
Scaffold(
appBar: AppBar(title: Text('タイトル')), // 上部のバー
body: Center(child: Text('メインコンテンツ')), // メイン画面
bottomNavigationBar: BottomNavigationBar(...), // 下部ナビゲーション
floatingActionButton: FloatingActionButton(...), // 浮いているボタン
drawer: Drawer(...), // 左側のメニュー
endDrawer: Drawer(...), // 右側のメニュー
bottomSheet: Container(...), // 下から出てくるシート
)
シンプルなものであれば、以下のように設定ができる。
Scaffold(
appBar: AppBar(title: Text('シンプル')),
body: Text('内容'),
)
AppBar
AppBarは、アプリの上部に表示されるバー。タイトルやナビゲーションボタン、 アクションボタン(検索フォームとかの)などを配置できる。
AppBar(
title: Text('タイトル'), // タイトル
leading: Icon(Icons.menu), // 左側のアイコン
actions: [ // 右側のアクション
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.more_vert),
onPressed: () {},
),
],
backgroundColor: Colors.blue, // 背景色
elevation: 4.0, // 影の高さ
centerTitle: true, // タイトルを中央揃え
)
例えば、Scafford
とAppBar
を以下のように実装することができる。
class MyPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('マイページ'),
// 左側:メニューボタン(自動で表示される場合が多い)
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.of(context).pop(); // 前の画面に戻る
},
),
// 右側:アクションボタン
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
print('検索ボタンが押されました');
},
),
PopupMenuButton(
itemBuilder: (context) => [
PopupMenuItem(child: Text('設定')),
PopupMenuItem(child: Text('ヘルプ')),
],
),
],
backgroundColor: Colors.indigo,
elevation: 8.0,
),
body: Center(
child: Text('ページの内容'),
),
);
}
}