6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutter初心者が、Flutter demoアプリを理解するまでの話

Last updated at Posted at 2021-10-12

初めに

私が初めて学習したプログラミング言語は、PC6601とかで動作するNECのBASICだった。古い話である。その後、Turbo C 2.0なるCコンパイラを入手してC言語を学習する。K&Rなんて本も読んだ。

Turbo C++ 1.01が高校生にも買えそうな値段だったのでこれを入手して使い始めたのが、オブジェクト指向の入門だった。今よりはずっと機能の少ないオブジェクト指向である。

お仕事始めたのがそんな時代である。困ったらアセンブリ言語使え、メモリーは貴重な資源だ、1バイトすら無駄にしない、みたいな時代である。たかだかputs()するだけなら数十バイトで実行プログラムはできるよね、みたいな時代だったなあ。

そんな私がFlutterを眺めると、まあいろいろと疑問は噴出する。もちろんおまじないだと思ってやり過ごしても構わない。1行ずつちゃんと理解しなくてもスマホに転送したアプリは動く。実際理解しようとすると泥沼にはまるのは目に見えているし、その時間は生産的活動ではないのですぐに止めたくなる。が、ちょっとやってみようかと思って書き始めた。前提としてC++の知識がおそらく必要だ。

サンプルアプリを見てみよう

$ flutter create firstrun

サンプルプロジェクトはできた。この中のlib/main.dartを見てみよう。

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // 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.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required 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
  State<MyHomePage> 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 a 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>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Windowsのプログラミングを始めたとき(Win32 APIをどうこうするなんて当たり前の時代よねえMFCなんてのもあったなあ)にも思ったんだけど、おまじないだらけだ。なにがなんなのかよくわからない。とりあえず整理しよう。

アプリケーションはどこから実行される?

C言語と同じだ。main()関数から実行される。どうやらこの言語も、どのクラスにも所属しない関数ってのがあるらしい。C++のmain()はそうである。ならば、その中身を見てみよう。

void main() {
  runApp(const MyApp());
}

なに? void main() { MyApp(); } じゃないのか?ただの関数実行じゃないのね?じゃ、runAppってどんなプロトタイプ(C++っぽい表現ね)なんだ?

調べてみると、Widget型のクラスを引数にとる関数である。ここでC++プログラマは思う。そうか、関数ポインタみたいなものなのか?Dart言語はクラスそのものを受け渡しできるようだ。コピーが作られて渡されるのか、参照で渡されてるのかポインタが渡されてるのかは調べていない。

ってことはだ、こんなコードも通るはずだよね。

sample1.dart
class Hoge {
  void hw() {
    print('Hello world');
  }
}

runHoge(Hoge h) {
  h.hw();
}

void main() {
  runHoge(Hoge());
}

はい、ちゃんと実行できる。なるほどねえ、Widget型のクラスの中のいろんなメソッドをじっこうしたりごにょごにょやってくれるのがrunApp()ってことよねえ、とりあえずmain()は困らない程度に理解した。次はWidget型のMyAPPクラスについて考えよう。

MyAppはどこまでシンプルにできるの?

世の中にあるサンプルプログラムというのは、サンプルに詰め込まれている要素が多くて理解を妨げることがある。このサンプルも、デモって書いてあるようにある程度の動きがないと面白くないので、そうなってるけど、純粋に文法理解とかするには要素が多すぎる。では削っていこう。

lib/main.dart
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

えっ?いきなり継承?

どうやらそういうことらしい。

さっきのサンプルをちょっと改造してみよう。

sample_extends.dart
class Hoge {
  void hw() {
    print('Hello world');
  }
}

runHoge(Hoge h) {
  h.hw();
}

class MyHoge extends Hoge {
  @override
  void hw() {
    print('こんにちは世界');
  }
}

void main() {
  runHoge(MyHoge());
}

はい、こちらも実行できる。なるほど、こうやってアプリケーションを書いていくのねえ。こちらはhw()というメソッドをオーバーライドすることで違う振る舞いをさせたわけだけど、FlutterのMyAppクラスは、build()メソッドをオーバーライドしてあげるわけね。じゃ、もちょっと。

buildの中身を観察

Widget型のクラスを返して、BuildContext型のクラスを引数に取るbuildメソッドを作るわけね。じゃだ、

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget w = Widget();
    return w;
  }
}

でもいいわけよね?

やってみるとわかるが、これはエラーになる。Widget型はAbstractクラスと呼ばれていて、インスタンス化できない。ここから先は、Dartのフレームワークの話に入らなければならないようだ。

最低限はなに?

要するに、画面になにか表示する最低限は何なのか?

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp();
  }
}

はい、真っ白なアプリができた。もうここまでわかってしまえば私が書きたいことは終わりである。あとは、Dartの文法とにらめっこしながら、あるいはAPIリファレンスを眺めながら、あるいはライブラリのリファレンスを眺めながらぼちぼち開発していけばよい。

おまけ

せっかくなので、Hello Worldを出しておこう。

lib/main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello world',
      home: Text('Hello World\nこんにちは世界')
    );
  }
}

最後に

中学生の時数学が苦手だった。解の公式とやらが理解できない、あんなの覚えられはしない。が、理科一般は好きだったし実際成績もよかった。おそらく私の性格は、上記のようにかなり基本的なところまで理解して身体化しなければたぶんすぐにわからなくなってしまうのだろう。当時独力で解の公式がちゃんと証明できていたならば私の数学人生はもうちょっと明るいものになっていたのかもしれない。

プログラミング言語はそれをまったくやったことのない人にとってはハードルがどんどん上がっているなと思う。結局概念を理解することであり、その理解しなければならない概念が年を追うごとにどんどん増えていく。BASICの時代はよかったなあ。上から下に実行されていくだけだもんなあ。

この文章、みんなが読みやすい気はしないけれど、一部の人にささるといいなあ。

6
10
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
6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?