Flutter公式チュートリアルのAdding interactivity to your Flutter appをやってみた
イントロダクション
Flutterの練習にチュートリアルをしました。 Adding interactivity to your Flutter app - 公式Tutorialを参考にしていきます。
目次
- イントロダクション
- 目次
- 学ぶこと
- Stateful and stateless widgets
- Creating a stateful widget
- Step 0: Get ready
- Step 1: Decide which object manages the widget’s state
- Step 2: Subclass StatefulWidget
- Step 3: Subclass State
- Step 4: Plug the stateful widget into the widget tree
- 作成したコード
- まとめ
- 参考サイト
学ぶこと
このチュートリアルでは、画面のお気に入りボタンを押すことができるようなウィジェットを作ります。
Stateful and stateless widgets
Statelessウィジェットはアイコンやテキストのように変化しない(静的なウィジェット)。 一方、statefullウィジェットはチェックボックス、テキストボックスのように動的に変化するウィジェットのこと。
Creating a stateful widget
ポイントは以下の通りです。
What's the point?
A stateful widget is implemented by two classes: a subclass of StatefulWidget and a subclass of State.
The state class contains the widget’s mutable state and the widget’s build() method.
When the widget’s state changes, the state object calls setState(), telling the framework to redraw the widget.
Step 0: Get ready
前回の記事を参考に、同様の環境を揃えます。
具体的には、flutter create
をして、lib/main.dart
、pubspec.yaml
を書き換え、lake.jpg
をフォルダに追加します。
初期画面は下のようになっているはずです。
Step 1: Decide which object manages the widget’s state
ウィジェットの管理の方法について。
Step 2: Subclass StatefulWidget
お気に入り状態を管理するため、FavoriteWidget
クラスを作成します。
main.dart
に以下を追記します。
class FavoriteWidget extends StatefulWidget { @override _FavoriteWidgetState createState() => _FavoriteWidgetState(); }
Step 3: Subclass State
お気に入り状態をタップで制御するため、以下のように_FavoriteWidgetState
を追加します。
class _FavoriteWidgetState extends State<FavoriteWidget> { bool _isFavorited = true; int _favoriteCount = 41; @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ Container( padding: EdgeInsets.all(0), child: IconButton( icon: (_isFavorited ? Icon(Icons.star) : Icon(Icons.star_border)), color: Colors.red[500], onPressed: _toggleFavorite, ), ), SizedBox( width: 18, child: Container( child: Text('$_favoriteCount'), ), ), ], ); } }
Step 4: Plug the stateful widget into the widget tree
アプリのウィジェットの中に先程作ったFavoriteWidget
を反映させます。
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { //... // Icon( // 削除 // Icons.star, // 削除 // color: Colors.red[500], // 削除 // ), // 削除 // Text('41'), // 削除 FavoriteWidget(), // 追加 // ...
画面のお気に入りボタンを押すと変化するようになります。
作成したコード
main.dart
をGistで共有します。
flutter tutorial, Adding interactivity to your Flu ...
また、Githubも共有します。
まとめ
だんだん形になってきました。次回からはアプリ開発を本格的に始めたいと思います。