LoginSignup
1
0

【Flutter】初期コード main.dart の中身を理解する

Last updated at Posted at 2023-11-23

目次

main.dart とは

ターミナルでアプリを作成したいフォルダに移動し$ flutter create 【任意のアプリ名】を実行すると、必要なファイルが自動的に生成される。
その中で生成される./lib/main.dartは、アプリを起動した際指定がないときに実行される。
(WEBサイトでいうとindex.htmlのようなもの?)

生成されるデフォルトのコード
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.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 THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // 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(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // 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.
          //
          // 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).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

分解して見ていく

import

import 'package:flutter/material.dart';

Flutter アプリ開発に必要なファイルをすべて包含しているファイルを呼び出す

void main()

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

Flutterで決められた最初に呼び出す関数。

class hogehoge extends fugafuga{}

class MyApp extends StatelessWidget {
  省略
}

fugafugaというclassを継承してhogehogeで使う
FlutterのWidgetではStatelessWidgetStatefulWidgetを継承する。
違いは見た目や値の変化を伴うかどうか。
(これに関しても記事を書く予定)

const MyApp({super.key});

const MyApp({super.key});
  • いろんな記事を見ていると(Key? key) : super(key: key)を見るときとsuper.keyを見ることがあるが、super.keyは、Flutter 3.0 に初めて付属した Dart 2.17 で利用可能になった新しい構文らしい。参考:FAQサイト
  • MyAppのコンストラクタでは、keyとリストいう名称でKeyクラスを受け取ることを可能としている。
  • MyAppのコンストラクタでオブジェクトを生成する際、このコンストラクタにMyAppのコンストラクタで受け取ったkeyを渡し初期化している。
  • super.keyばカスタムウィジェットのコンストラクタで、親クラスのコンストラクタにkeyを渡す際に使用される。指定がなければ親クラスのコンストラクタのkeyを使用する。

@override

@override

親クラスのものを継承しているけど、以下上書きしていくよ、という目印。
なくても上書きされるが、あったほうが問題があったときに見つかりやすい。(らしい。まだ問題が発生するとコマでできてないからありがたみをわかってない)

Widget build(BuildContext context) {}

Widgetツリーに対してどこで使うWidgetなのかを明示している。
下記ならMaterialAppというhtmlとかbodyに当たるようなルート。return ScaffoldとなっていればにMaterialApp入る親要素で使用されることになる。

  Widget build(BuildContext context) {
    return MaterialApp(
      // MaterialApp 
    )
  }

return MaterialApp()

構成しているもの 説明
StatelessWidget 親クラス
MyApp 子クラス
buildメソッド 子クラス内のメソッド
MaterialApp Material Designアプリケーションのルートウィジェット。アプリ全体で共通のテーマやナビゲーション、ローカリゼーションなどの設定が簡単にできる。<html><body>のようなもの?
ルートになるウィジェットを返すよ、の意味
  return MaterialApp(
    title: 'Flutter Demo', // head内のtitleのような役割
    theme: ThemeData( 
      // アプリケーション全体で使用するデザインやカラーパレット、テキストスタイルなどを定義する
    ),
    home: const MyHomePage(title: 'Flutter Demo Home Page'), // bodyに当たる部分?''の間H1に当たるものを入れることが多そう。AppBarなどに入れたりできる。
  )

ThemeData()

  ThemeData(
    colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), // seedColorを起点として関連色を決めてくれるらしい
    useMaterial3: true, // Material Design 3に適合したColor systemをアプリに適用
  )

アプリケーション全体で使用するデザインやカラーパレット、テキストスタイルなどを定義する

class MyHomePage extends StatefulWidget {}

  • StatefulWidgetを継承しているので状態を管理している。
  • const MyHomePage({super.key, required this.title});

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title}); // 親クラスにkeyとtitleを渡す
  final String title; // title を文字列(string)として一度だけ代入
  @override // 以下上書き
  State<MyHomePage> createState() => _MyHomePageState(); // MyHomePage のStateとして_MyHomePageStateを呼び出す
}

const と final の違い

  • constは代入不可で不変の定数
  • finalはclass内で一度しか代入しないときに使われる

class _MyHomePageState extends State {}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0; // int(整数)を定義。少数を使いたいときはdouble
  void _incrementCounter() { // void は return なし
    setState(() { // 保持しているデータを更新
      _counter++; // 1ずつ足す
    });
  }
  @override // 上書き
  Widget build(BuildContext context) { // Scaffold で使う Widget
    return Scaffold( // Scaffoldはbody や main に近い
      appBar: AppBar( // header に近い
        backgroundColor: Theme.of(context).colorScheme.inversePrimary, // プライマリカラーで設定されたinversePrimaryのStyleを取得して背景色に反映
        title: Text(widget.title), // MyHomePage objectからtitleに反映
      ),
      body: Center( // main に近い Centerなので中央に寄る
        child: Column( // 子要素。縦に並ぶ。
          mainAxisAlignment: MainAxisAlignment.center, // フレックスレイアウト Column なので縦に並んでいる要素の配置を中央にする
          children: <Widget>[ // child と違い childrenは複数のwidgetを持てる
            const Text( // text
              'You have pushed the button this many times:', // 任意のtext
            ),
            Text( // text
              '$_counter', // 変数を文字列保管する場合は 変数の先頭に $ をつけることで行うことが出来る
              style: Theme.of(context).textTheme.headlineMedium, // textThemeで指定されているheadlineMediumのスタイルを採用
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton( // 画面右下に浮いてるボタン
        onPressed: _incrementCounter, // 押されたときのアクション。_incrementCounterは前述で設定した通り_counterを1ずつ足すよう更新するやつ。
        tooltip: 'Increment', // 長押しするとでてくるツールチップ内のテキスト
        child: const Icon(Icons.add), // 子要素にアイコンを設定
      ), 
    );
  }
}

body: Center()

bodyは以下4つから任意の値を設定できる

  • body: Row()
    • 子要素を横に並べる
  • body: Column()
    • 子要素を縦に並べる
  • body: Center()
    • 子要素の横または縦を真ん中に位置させる
      • 子要素がRowなら縦に対しては真ん中だが横は寄っていたり、Columnなら横に対しては真ん中だが縦が上に寄っていたりする。mainAxisAlignmentを指定して調整可能。
  • body: Container ()
    • 子要素のサイズやpadding,marginなどの設定ができる。

感想

  • 完璧に理解できているわけではないけど、ようやく全貌がふわっと見えてきた気がする。
  • 自分にとってわかりやすい記事をガンガン探すスタイルが自分には向いてる。。硬い文章にがて。。
  • ところどころそのままソースを検索しても、アップデートされてるから今は違う、みたいなところもあった。研鑽大事。
    • 公式ドキュメントのみでできればいいけど、頭の余裕がないときのほうが多い。南無。
  • ツリー構造をきちんと理解したい。

参考

1
0
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
1
0