LoginSignup
2
2

More than 5 years have passed since last update.

flutterメモ

Posted at

対象ソース

https://flutter.io/docs/get-started/install
なんかこのツアーのどこかのタイミングで生成されたソースだった気がする。
どのタイミングで生成されたのか全く覚えてないが、まぁ良いだろう。
このソースはこんな感じに見えるカウンターアプリである。

スクリーンショット 2019-01-13 2.45.03.png

import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.amber,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              WordPair.random().asPascalCase,
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

親切にコメントがついてるので、自分の為にも1つ1つ解説してみようと思う。

1. $ flutter runでプロジェクトを立ち上げられるよ。

IOSシュミレーターが立ち上がっていない場合$ open -a Simulatorで立ち上げよう。
vscodeだとファイル保存時に2019年1月の今だとhot reloadingが何故か走らないバグが起きているが、まぁいつか解決するんじゃないかな。
flutter runを叩いたコンソールでrコマンドを叩くとhot reloadingされるのでまぁ手動で頑張るかって感じ。もしきつかったらAndroid Studioがhot reloadingバグってなければ選択肢として考慮せねば。

2. 基本的にコンポーネント指向ならずWidget指向っぽい

FlutterだとStatelessWidgetStatefulWidgetの2つのどちらかのWidgetしか存在しない(多分)。
この2つのWidgetの実装は抽象クラスである。
それらを継承して実装したWidgetは必ずbuildメソッドをオーバーライドして実装する必要がある。
見た感じ多分このbuildメソッドはReactやVueで言う所のrenderメソッドと同義のはず。

3. primarySwatchにテーマカラーを入れるとその色にしてくれる。

俺はvuetify使って開発してるからわかるが、これは絶対に動的に色を変えられるやつや。。。!良さげ。

4. MyHomePageconstructortitle受け取って_MyHomePageStateがそれを参照してる

なんかclassが微妙に依存関係があって気持ち悪い。
しかも1つのwidgetを作るのに分解してる感じ。
しかし地味に責任分界してるのでなんとも言えない。
なんかextends地獄の気配がするのでこの辺はfunctional componentとかもしくはvueみたいなもうちょっとワンセット感でる感じでできないかなーと思った。

5. setStateはReactのsetStateと同じ

setStateの項目をgoogle翻訳するとこんな感じの文書になる。

このsetStateの呼び出しは、この状態で何かが変更されたことをFlutterフレームワークに伝えます。これにより、表示が更新された値を反映できるように、以下のbuildメソッドが再実行されます。 setState()を呼び出さずに_counterを変更した場合、buildメソッドは再度呼び出されないため、何も起こりません。

やっぱりbuildはrenderであり、setStateはReactのsetStateと同じ仕事や。
後この文書みるとbuildは良い感じに最適化されてるっぽい。
ちなみにwidgetには全てkeyも付けれたので、それで一応こちらから特定widgetの同一性コントロールもできそう。

例えば上記の_incrementCounterメソッドによって行われるように、このメソッドはsetStateが呼び出されるたびに再実行されます。

Flutterフレームワークは、ビルドメソッドの再実行を高速化するように最適化されているため、ウィジェットのインスタンスを個別に変更する必要はなく、更新が必要なものはすべて再構築できます。

6. title: Text(widget.title),のwidgetはMyHomePageのtitleを指してる

7. Centerはレイアウトウィジェットです。 1人の子供を取り、それを親の真ん中に配置します。

8

列もレイアウトウィジェットです。 それは子供のリストを取り、それらを縦に並べます。 デフォルトでは、それはその子を水平方向にフィットするようにそれ自身をサイズ変更し、その親と同じくらいの高さにしようとします。

各ウィジェットのワイヤフレームを表示するには、「debug painting」を起動します(コンソールで「p」を押し、Android Studioの「Flutter」インスペクタから「Toggle Debug Paint」アクションを選択するか、「Toggle Debug Paint」コマンドを選択します)。 。

Columnには、それ自体のサイズや子の位置を制御するためのさまざまなプロパティがあります。 ここではmainAxisAlignmentを使用して子を垂直方向に中央揃えします。 ここでは主軸は垂直軸です。列は垂直です(横軸は水平になります)。

纒め

やってることは大体わかった気がする。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2