Flutterでようやく実用的なアプリが作れるようになってきたので、次のアプリ開発の参考までに開発したアプリのコードをメモしておきます。サイコロをタップしてランダムな目を出すことができるアプリです。
pubspec.yamlの記述
画像ファイルを読み込むための記述を描きました。
55行目のflutter:
以降に画像ファイルが入っているフォルダをしているすればオッケーです。
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
#imagesフォルダーを依存関係に追加する
assets:
- images/
main.dartのコード
//Mathをインポートする
import 'dart:math';
import 'package:flutter/material.dart';
//ダイスを振ってランダムで表示するアプリ
//スカフォールドウィジェットの中にステートフルウィジェットをオーバーライドして埋め込む
void main() {
return runApp(
MaterialApp(
home:Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
title: Text("Dicee"),
backgroundColor: Colors.red,
),
body: DicePage(
),
),
),
);
}
//変数を操作するタイプのアプリを作る場合は、ステートフルウィジェットにする
//ステートフルにすると、変数が更新された際にステートフルウィジェット全体が更新される
class DicePage extends StatefulWidget{
@override
_DicePageState createState() => _DicePageState();
}
//ウィジェットの中のクラスをオーバーライドする
class _DicePageState extends State<DicePage> {
int leftDiceNumber01 = 1;
int leftDiceNumber02 = 6;
//変数の更新は関数を使って簡略化する
void changeDiceFace(){
setState((){
leftDiceNumber01 = Random().nextInt(6) + 1;
leftDiceNumber02 = Random().nextInt(6) + 1;
});
}
@override
Widget build(BuildContext context){
//サイコロを表示するロウを作成する
return Center(
child: Row(
children: <Widget>[
Expanded(
child:Padding(
padding: const EdgeInsets.all(10.0),
child: MaterialButton(
//イメージを変更する
onPressed: (){
changeDiceFace();
},
child: Image(
image: AssetImage("images/dice$leftDiceNumber01.png"),
),
),
),
),
Expanded(
child:Padding(
padding: const EdgeInsets.all(10.0),
child: MaterialButton(
onPressed: (){
changeDiceFace();
},
child: Image(
image: AssetImage("images/dice$leftDiceNumber02.png"),
),
),
),
),
],
),
);
}
}
Flutterではステートフル・ステートレスという概念があり、ステートレスなウィジェットはウィジェット内のクラスの変数が変更されるとそれに伴いウィジェット自体がすべて更新される、という処理を行えるようになってます。変数を変更するたびに画像や表示するウィジェットを更新する関数を駆動しなくても良い設計ができる訳ですね。