技術的備忘録

基本自分用備忘録

Flutter ListでのforEach内での非同期処理

Flutterで複数選択されたオブジェクトをforeachで個々に非同期処理をしたい際にちょっとはまったのでメモ

実際のコード

  Future<void> hogeHoge() async {
    await Future.forEach(this.hogeIdList, (hogeId) async {
      // 非同期で行いたい処理
      await this.hoge(hogeId);
    });
    notifyListeners();
  }

参考

patorash.hatenablog.com

Flutter Widgetまとめ① StatefulWidget

StatefulWidget

  • レイアウトやアニメーションを使った場合でも、高速にレンダリングしたい場合に使用する
  • 簡単な処理だけを行うウィジェットでStatefulWidgetを使用し、状態管理する場合はシンプルなコードで読みやすい
  • 処理が増えてきて、ロジックが肥大化してくると、描画と処理がごちゃごちゃして、どこで何が行われているか分かりづらく、読みづらいコードになる

api.flutter.dev

StatefulWidgetを作成する際に必要なクラスは以下の2つ

  • StatefulWidgetを継承したクラス
  • Stateを継承したデータクラス

StatefulWidgetを継承したクラス

  • createState()でStateを継承したクラスを返す
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

Stateを継承したクラス

  • 変数を更新する場合は、setState()を呼び出す
  • setStateで変数が更新され、画面が再buildされる
  • StatefulWidgetで定義されている変数にアクセスする場合は、widget.変数名
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          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),
      ),
    );
  }
}

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: 'Flutter Demo',
      theme: ThemeData(
        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);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

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

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          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),
      ),
    );
  }
}

Flutter 環境構築

Flutterの環境構築は必要なものが少し多くて、ややこしいのでまとめておこうと思います。 Windows版です。

FlutterSDKのダウンロード

  • 公式サイトからダウンロード・解凍します
  • ダウンロード後、環境変数にPathを通します

docs.flutter.dev

Flutter doctorコマンドの実行

  • Flutterのパスを通したフォルダで以下コマンドを実行します
  • flutter doctor
  • 開発環境構築で不足しているものがわかります

f:id:syoch:20220310060943p:plain

  • VisualStudioはデスクトップアプリの開発に必要ですが、今回は省きます

AndroidStudioのインストール

  • 公式サイトからダウンロード・インストールをします

developer.android.com

Androidライセンスの承認

  • 以下コマンドを実行します
  • flutter doctor--android-licenses

Androidエミュレーターの作成

f:id:syoch:20220310062240p:plain

f:id:syoch:20220310062258p:plain

f:id:syoch:20220310062307p:plain

f:id:syoch:20220310062319p:plain

f:id:syoch:20220310062329p:plain

f:id:syoch:20220310062421p:plain

VisualStudioCodeのダウンロード

  • 公式サイトからダウンロードします

azure.microsoft.com

拡張機能のインストール

  • FlutterとDartをインストールしておきます

f:id:syoch:20220310063126p:plain

プロジェクトの作成

  • ctrl + shift + p から Flutter: New Project を選択します

f:id:syoch:20220310063413p:plain

  • Applicationを選択 f:id:syoch:20220310063506p:plain

  • ディレクトリを選択して、プロジェクト名を入力します f:id:syoch:20220310063705p:plain

アプリの実行

f:id:syoch:20220310063918p:plain

f:id:syoch:20220310070536p:plain

f:id:syoch:20220310072401p:plain

  • main.dartを開いた上で、F5キーを押すとエミュレーターにインストールされアプリが起動します

f:id:syoch:20220310072600p:plain

Flutter DropdownButtonにFirebaseから取得したjsonのリストを指定する

DropdownButtonの使い方

api.flutter.dev

  • Firebaseから取得したオブジェクトの形式
{
  name: 'AAA',
  order: 1,
  folderId: 'id'
}

実際のコード

DropdownButton作成

DropdownButton<String>(
  value: model.selectFolderId,
  hint: Text('フォルダ'),
  icon: const Icon(Icons.arrow_downward),
  elevation: 16,
  style: const TextStyle(color: Colors.deepPurple),
  underline: Container(
  height: 2,
  color: Colors.deepPurpleAccent,
  ),
  onChanged: (String newValue) {
    model.setFolderId(newValue);
  },
  items: _getDropdownMenuItemList(this.folderList)
)

表示メニューを返す関数

List<DropdownMenuItem<String>> _getDropdownMenuItemList(folderList) {
  var dropdownList = <DropdownMenuItem<String>>[];
  dropdownList
      .add(new DropdownMenuItem<String>(value: '', child: Text('選択しない')));
  if (model.folderList != null && folderList.length > 0) {
    for (var folder in folderList) {
      dropdownList.add(new DropdownMenuItem<String>(
          value: folder.folderId, child: Text(folder.name)));
    }
  }
  return dropdownList.toList();
}

ドロップダウンのリストに表示するのはnameで、選択されたときに格納する値はfolderIdを指定する。 provider側で最新のフォルダリストを取得し、DropdownButtonのitemsにリストを表示する。 DropdownMenuItemを別関数からList<DropdownMenuItem>の形で返すことで、リスト最上部にデフォルト値を追加できた。

f:id:syoch:20220111083445p:plain

f:id:syoch:20220111083517p:plain

Flutter theme アプリ共通カラーコード・スタイル設定

  • Flutterの共通スタイルはMaterialAppのルートウィジェットにthemeを設定する
  • ダークモードにもthemeで対応できる

main.dart

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: createTheme(),
      debugShowCheckedModeBanner: false,
      home: SignUpPage(),
    );
  }
}

docs.flutter.dev

  • themeに設定できるプロパティはけっこう多い themeを返す関数
import 'package:flutter/material.dart';

ThemeData createTheme() {
  return ThemeData(
    primarySwatch: Colors.blue,
  );
}

api.flutter.dev

  • colorコード定義
import 'package:flutter/material.dart';

class ThemeColors {
  static const baseColor = const Color(0xFF222831);
  static const accentColor = const Color(0xFFFD7013);
  static const subColor = const Color(0xFF393E46);
  static const textColor = const Color(0xFFEEEEEE);
}

api.flutter.dev

Flutter 汎用ダイアログを表示する

Flutterでのダイアログ表示

Flutterでのダイアログ表示には、showDialogメソッドを使用します。

api.flutter.dev

複数個所で呼び出す必要があったため、別ファイルにメソッドとして切り出して使用しています。

ダイアログ表示
ダイアログ表示

Future<bool> showCommonDialog(BuildContext context, String title,
    String message, String yesText, String noText) async {
  return await showDialog(
      context: context,
      builder: (BuildContext context) {
        return WillPopScope(
            onWillPop: () async => false,
            child: AlertDialog(
              title: Text('$title'),
              content: Text('$message'),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.pop(context, false);
                  },
                  child: Text(noText),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                  child: Text(yesText),
                ),
              ],
            ));
      });
}
  • 引数は
    • BuildContext
    • タイトル用文字列
    • 表示するメッセージ
    • 「はい」部分に表示する文字列
    • 「いいえ」部分に表示する文字列
  • 返り値は「はい」「いいえ」のどちらかをタップしたかを true/false で返却します
  • ユーザーがクリックするまで、呼び出し元の処理を待機させてます
  • WillPopScopeでfalseを指定しているのは、画像のグレー部分をタップ、または戻るボタン等「はい」「いいえ」のタップ以外でダイアログ表示を終了させないためです

呼び出し元

onPressed: () async {
  var result = await showCommonDialog(
        context, '保存しますか?', '変更は保存されていません。', '保存する', '保存しない');
  if (result) {
    // 「はい」選択時の処理
  } else {
    // 「いいえ」選択時の処理
  }
},

Flutter Widget ListView

ListView

  • スクロール可能なウィジェットのリスト
  • ListView.builderを使用して作成することで、動的なリストが作成できる
  • ListView.separatedを使用して作成することで、リストの要素の間に区切りを設定することができる api.flutter.dev

普通のListView

  • ListViewに表示される可能性のあるすべての子要素に対して処理を行うため、子要素の数が少ないリストに適している
  • 子要素の数が変更される場合があるなら、ListView.builderを使ったほうがいい

  • 公式サンプルコード

ListView(
  padding: const EdgeInsets.all(8),
  children: <Widget>[
    Container(
      height: 50,
      color: Colors.amber[600],
      child: const Center(child: Text('Entry A')),
    ),
    Container(
      height: 50,
      color: Colors.amber[500],
      child: const Center(child: Text('Entry B')),
    ),
    Container(
      height: 50,
      color: Colors.amber[100],
      child: const Center(child: Text('Entry C')),
    ),
  ],
)

ListView.builder

  • 表示する子要素を事前に用意しておく必要がないので、多くの子要素を持つリストや、動的なリストの表示に使用する
  • itemBuilderには、非Nullのウィジェットを設定し、ウィジェットインスタンスを返すようにする。
  • 子要素の並び替えはサポートしていないので、後から子要素の順番を変更する場合は、ListViewやListView.customを使用したほうがいいらしい
  • itemBuilderの指定は必須

  • 公式サンプルコード

final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];

ListView.builder(
  padding: const EdgeInsets.all(8),
  itemCount: entries.length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      height: 50,
      color: Colors.amber[colorCodes[index]],
      child: Center(child: Text('Entry ${entries[index]}')),
    );
  }
);