省エネ

Flutter、vue3修行中。

FlutterでMaterialを使わないという選択。WidgetsAppでWebアプリを作ってみた

こんにちは。
黒猫です。 FlutterといえばMaterialデザインと思っていませんか?
今回はFlutter webのアプリをMaterialを使わずに作るという試みをしてみました。

MaterialAppじゃなくてWidgetsAppを使う

main.dartの最初のWidgetにはMaterialAppを使っている方が多いのではないでしょうか?
Flutterサンプルがそうなっているのでそのまま使用してるんじゃないかと思います。
Flutter 3.47から、MaterialとCupertinoのデザインライブラリがFlutter SDKから独立し、それぞれ material_uiと cupertino_ui というパッケージとして提供されるようになりました。
Flutter 3.50では、従来のSDKに含まれていたMaterialとCupertinoのライブラリが非推奨になっています。
Material Widgetを使う場合は material_ui を、Cupertino Widgetを使う場合は cupertino_ui を利用する形になります。
この機会に、Material Widgetに依存せず、Flutter標準の widgets.dartに含まれるWidgetを使ってアプリを作り直してみることにしました。

環境

flutter version: 3.50.0

---

dependencies:
  flutter:
    sdk: flutter
  flutter_web_plugins:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.8
  go_router: ^18.1.4
  riverpod_annotation: ^4.0.8
  flutter_riverpod: ^3.5.0
  hooks_riverpod: ^3.5.0
  freezed_annotation: ^3.1.0
  google_fonts: ^6.3.0
  flutter_oss_licenses: ^3.0.4
  flutter_hooks: ^0.21.3+1
  intl: ^0.20.3
  supabase_flutter: ^2.10.2
  url_launcher: ^6.3.2

コードはこんな感じです。

    return WidgetsApp.router(
      routerConfig: routes,
      title: '城Navi',
      color: AppColors.navy,
      debugShowCheckedModeBanner: false,
      builder: (context, child) {
        return DefaultTextStyle(
          style: const TextStyle(
            fontFamily: 'NotoSansJP',
            fontSize: 14,
            color: Color(0xFF17243A),
          ),
          child: child ?? const SizedBox.shrink(),
        );
      },
    );

go routerを使っているのでWidgetsApp.router()にしています。
これで、Materialを使わない準備は完了です!

メリットデメリット

Materialを使わないメリット

  • デザインの自由度が高い
  • Webサイトに合わせた独自UIを作りやすい
  • Material独自のテーマや装飾に依存しない
  • 必要な機能だけを自分で実装できる

    デメリット

  • 標準Widgetを自作する手間がある
  • フォーカスや入力制御なども自分で考える必要がある
  • アクセシビリティへの配慮が必要
  • ダイアログやボタンなどの共通部品を自分で管理する必要がある

普段使っているWidgetが使えなくなる

WidgetsAppにするといつも使っているWidgetが使えなくなることがあります。
今回、MaterialAppで作っていたアプリをWidgetsAppに置き換えたのですが、使えなくなったWidgetはこのくらいあります。

  • Scaffold
  • AppBar
  • Drawer
  • Card
  • TextField
  • CircularProgressIndicator
  • AlertDialog
  • Divider
  • ElevatedButton
  • TextButton
  • Icons
  • Colors

これを一つ一つ、WidgetsAppで使えるWidgetを使って置き換えていきます。
その中でもコピペですぐ使えそうな自作Widgetについて紹介します!

Button

ElevatedButtonやTextButtonなどMaterialに依存するボタン類は使えないので自作します。 なお、カラーパレットは別で定義してあります。

import 'package:flutter/widgets.dart';

import '../theme/app_colors.dart';

class AppButton extends StatelessWidget {
  const AppButton({
    super.key,
    required this.label,
    required this.onPressed,
    this.backgroundColor,
    this.foregroundColor = const Color(0xFFFFFFFF),
    this.fontSize = 16,
    this.fontWeight = FontWeight.bold,
    this.horizontalPadding = 28,
    this.verticalPadding = 16,
    this.borderRadius = 8,
    this.width,
    this.height,
  });

  final String label;
  final VoidCallback? onPressed;

  final Color? backgroundColor;
  final Color foregroundColor;

  final double fontSize;
  final FontWeight fontWeight;
  final double horizontalPadding;
  final double verticalPadding;
  final double borderRadius;

  final double? width;
  final double? height;

  @override
  Widget build(BuildContext context) {
    final isEnabled = onPressed != null;

    return GestureDetector(
      onTap: onPressed,
      behavior: HitTestBehavior.opaque,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 150),
        width: width,
        height: height,
        padding: EdgeInsets.symmetric(
          horizontal: horizontalPadding,
          vertical: verticalPadding,
        ),
        decoration: BoxDecoration(
          color: isEnabled
              ? backgroundColor ?? AppColors.gold
              : const Color(0xFFBDBDBD),
          borderRadius: BorderRadius.circular(borderRadius),
        ),
        alignment: Alignment.center,
        child: Text(
          label,
          style: TextStyle(
            color: foregroundColor,
            fontSize: fontSize,
            fontWeight: fontWeight,
          ),
        ),
      ),
    );
  }
}

TextField

TextFieldはEditableTextというWidgetを使って作成します。
このコードは入力だけじゃなく装飾の部分も梱包しています。

import 'package:flutter/widgets.dart';

class AppTextField extends StatefulWidget {
  const AppTextField({
    super.key,
    this.controller,
    this.hintText,
    this.label,
    this.maxLines = 1,
    this.minLines = 1,
    this.keyboardType,
    this.obscureText = false,
    this.enabled = true,
    this.onChanged,
  });

  final TextEditingController? controller;
  final String? hintText;
  final String? label;
  final int maxLines;
  final int minLines;
  final TextInputType? keyboardType;
  final bool obscureText;
  final bool enabled;
  final ValueChanged<String>? onChanged;

  @override
  State<AppTextField> createState() => _AppTextFieldState();
}

class _AppTextFieldState extends State<AppTextField> {
  final FocusNode _focusNode = FocusNode();

  late TextEditingController _controller;
  bool _ownsController = false;

  @override
  void initState() {
    super.initState();

    _setController();
    _focusNode.addListener(_onFocusChanged);
  }

  void _setController() {
    _controller = widget.controller ?? TextEditingController();
    _ownsController = widget.controller == null;
  }

  @override
  void didUpdateWidget(covariant AppTextField oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (oldWidget.controller != widget.controller) {
      if (_ownsController) {
        _controller.dispose();
      }
      _setController();
    }
  }

  void _onFocusChanged() {
    setState(() {});
  }

  @override
  void dispose() {
    _focusNode.removeListener(_onFocusChanged);
    _focusNode.dispose();

    if (_ownsController) {
      _controller.dispose();
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isFocused = _focusNode.hasFocus;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (widget.label != null) ...[
          Text(
            widget.label!,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Color(0xFF292724),
            ),
          ),
          const SizedBox(height: 8),
        ],
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 15),
          decoration: BoxDecoration(
            color: const Color(0xFFFFFFFF),
            borderRadius: BorderRadius.circular(10),
            border: Border.all(
              color: isFocused
                  ? const Color(0xFFB2944A)
                  : const Color(0xFFDED7CD),
              width: isFocused ? 1.5 : 1,
            ),
          ),
          child: Stack(
            alignment: Alignment.centerLeft,
            children: [
              if (widget.hintText != null && _controller.text.isEmpty)
                IgnorePointer(
                  child: Text(
                    widget.hintText!,
                    style: const TextStyle(
                      color: Color(0xFFAAA49B),
                      fontSize: 15,
                    ),
                  ),
                ),
              EditableText(
                controller: _controller,
                focusNode: _focusNode,
                style: TextStyle(
                  fontSize: 15,
                  color: widget.enabled
                      ? const Color(0xFF292724)
                      : const Color(0xFF999999),
                ),
                cursorColor: const Color(0xFFB2944A),
                backgroundCursorColor: const Color(0xFF292724),
                keyboardType: widget.keyboardType,
                obscureText: widget.obscureText,
                maxLines: widget.maxLines,
                minLines: widget.minLines,
                readOnly: !widget.enabled,
                onChanged: (value) {
                  setState(() {});
                  widget.onChanged?.call(value);
                },
              ),
            ],
          ),
        ),
      ],
    );
  }
}

AlertDialog

showDialog()も使えなくなるのでshowGeneralDialog()を使います。
それも梱包した状態で作成しました。

import 'package:flutter/widgets.dart';

class AppDialog {
  static Future<T?> show<T>({
    required BuildContext context,
    required String title,
    required String message,
    String cancelText = 'キャンセル',
    String confirmText = 'OK',
    VoidCallback? onCancel,
    VoidCallback? onConfirm,
    bool barrierDismissible = true,
  }) {
    return showGeneralDialog<T>(
      context: context,
      barrierDismissible: barrierDismissible,
      barrierLabel: 'Dialog',
      barrierColor: const Color(0x80000000),
      transitionDuration: const Duration(milliseconds: 200),
      pageBuilder: (context, animation, secondaryAnimation) {
        return Center(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Container(
              constraints: const BoxConstraints(
                maxWidth: 400,
              ),
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: const Color(0xFFFFFFFF),
                borderRadius: BorderRadius.circular(16),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF17243A),
                    ),
                  ),
                  const SizedBox(height: 16),
                  Text(
                    message,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Color(0xFF333333),
                    ),
                  ),
                  const SizedBox(height: 24),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      GestureDetector(
                        onTap: () {
                          onCancel?.call();
                          Navigator.of(context).pop();
                        },
                        child: Padding(
                          padding: const EdgeInsets.all(12),
                          child: Text(cancelText),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          onConfirm?.call();
                          Navigator.of(context).pop(true);
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 20,
                            vertical: 12,
                          ),
                          decoration: BoxDecoration(
                            color: const Color(0xFF17243A),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            confirmText,
                            style: const TextStyle(
                              color: Color(0xFFFFFFFF),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
      transitionBuilder: (context, animation, secondaryAnimation, child) {
        return FadeTransition(
          opacity: animation,
          child: ScaleTransition(
            scale: Tween<double>(
              begin: 0.95,
              end: 1,
            ).animate(animation),
            child: child,
          ),
        );
      },
    );
  }
}

CircularProgressIndicator

実はこれもMaterialのWidgetです。
これは、`CustomPainterを使いました。

import 'dart:math' as math;
import 'package:flutter/widgets.dart';

class CustomCircularIndicator extends StatefulWidget {
  const CustomCircularIndicator({
    super.key,
    this.size = 36,
    this.strokeWidth = 3,
    this.color = const Color(0xFFB2944A),
  });

  final double size;
  final double strokeWidth;
  final Color color;

  @override
  State<CustomCircularIndicator> createState() =>
      _CustomCircularIndicatorState();
}

class _CustomCircularIndicatorState
    extends State<CustomCircularIndicator>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000),
    )..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.size,
      height: widget.size,
      child: AnimatedBuilder(
        animation: _controller,
        builder: (context, child) {
          return CustomPaint(
            painter: _CircularIndicatorPainter(
              progress: _controller.value,
              color: widget.color,
              strokeWidth: widget.strokeWidth,
            ),
          );
        },
      ),
    );
  }
}

class _CircularIndicatorPainter extends CustomPainter {
  _CircularIndicatorPainter({
    required this.progress,
    required this.color,
    required this.strokeWidth,
  });

  final double progress;
  final Color color;
  final double strokeWidth;

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..strokeCap = StrokeCap.round;

    final rect = Rect.fromLTWH(
      strokeWidth / 2,
      strokeWidth / 2,
      size.width - strokeWidth,
      size.height - strokeWidth,
    );

    canvas.drawArc(
      rect,
      -math.pi / 2 + progress * 2 * math.pi,
      math.pi * 1.5,
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant _CircularIndicatorPainter oldDelegate) {
    return oldDelegate.progress != progress ||
        oldDelegate.color != color ||
        oldDelegate.strokeWidth != strokeWidth;
  }
}

実際にやってみて

Material Widgetを使わずにアプリを作るのは、思っていたよりも手間がかかりました。
特に入力フォームやダイアログなど、普段は当たり前のように使っていたWidgetを自分で作る必要があります。 ただ、その分デザインの自由度は高くなり、Webサイトに合わせたUIを自由に作れるようになりました。 すべてのアプリでMaterialを使わない方がいいとは思いませんが、Webアプリなど独自のデザインを重視したい場合には、こういう選択肢もありだと思います。

まとめ

MaterialやCupertinoを使わずにも自由な発想でアプリを作成できることがわかりました!
Webアプリなのでモバイルのデザインに引きずられないようなデザインにしたかったこと。
Flutterのバージョンを上げたことにより、MaterialとCupertinoが分離するバージョンになったこともきっかけになり、もういっそ使わない方向にしてみようかなと思い実装に至りました。 まだリリースできていませんが、いずれWidgetsAppで作ったアプリを公開したいと思います。
ここまで読んでいただきありがとうございました。

【AI】個人開発とAI

こんにちは。
今回は個人開発アプリ「城Navi」をAIに手伝ってもらって開発した話を書きたいと思います。

エンジニアくそださUI問題

個人開発アプリ「城Navi」のv1.4.0をGooglePlayへ公開しました!
iosは現在審査中です。

play.google.com

以前の城Naviはとても簡素なデザインでした。

v1.0.0の城Navi

シンプルすぎる。
かといってデザイナーさんへ依頼するほどの資金もなく、アプリ自体も売り上げをあげられている訳ではないのでなかなか頼みづらい。

今回のバージョンではChatGPTにデザインを考えてもらいました。

それがこちら!

v1.4.0の城Navi

ヘッダーに表示している画像なんかもChatGPTに作ってもらいました。
どうでしょう。
だいぶ様になってきたと思いませんか?

Supabaseよく分からない問題

supabaseというBaaSがあるのはご存知でしょうか?
比較的安価でpostgresqlが使えます。
城Naviにはsupabaseを使用しています。
ドキュメントもしっかりしていますが、正直なかなかキャッチアップは大変。
RSLPolicyの付け方とかもよく分からない。
普段、フロントばかりやっているので正直DBよく分からない。
そんな私でもChatGPTがいればいい感じにテーブル設計をし、クエリを書いてデータのやり取りができます!
チャッピー様様です。

ストア公開への手ほどきもしてくれる

以前からandroidアプリを公開した経験があるので、androidは比較的簡単に公開できました。
(GooglePlayConsoleメニューがどこにあるのかよく分からない問題はある). 今回、初めてiosアプリの公開(現在審査中)にふみきりました。

ストアの設定がよく分からず、どこに何を書いていいのやら。
ほぼほぼチャッピーに教えてもらいながら設定しました。
頼もしい相棒です。

以前だったらやり方が分からないところがあったら調べるのに時間がかかったり、諦めちゃったりしてたかもです。
あっという間に審査までこぎつけられました。

個人アプリを華やかにしてくれる

正直、画像などを作成するのが苦手なのです。
アプリに色つけるアイコンやヘッダー画像などは全てChatGPTに作成してもらいました。

Google Play向けの掲載画像は自分でCanvaを使って作りましたが、ios向けのストア用の画像はChatGPTに作ってもらいました。
Canvaと連携させて、以前私が作ったandroid向けの画像に似た色味で作ってくれました。
他サービスとの連携でもっと色々できそうですね。

コードも書いてくれる

v1.3.0〜v1.4.0の修正はほぼほぼChatGPTに書いてもらいました。
Flutterでこんなコンポーネントを作ってほしいなどとお願いするとあっという間に書いてくれます。
以前からGithubCopilotの補完機能は使っていましたが、チャットで対話型でさくっと作ってもらえるのはとても便利ですね。
うまくいってないコードを貼り付けてここなおして、とか、nullになりそうな怪しいコードのチェックをしてもらったりなど大活躍でした。
supabseでのselectやinsertなんかもさくっと書いてくれます。
以前みたいにドキュメントを読みながら自分で書くよりあっという間にアプリの修正ができました。
普段から私のコードを読ませているので私の好きな書き方を真似してくれるのも好感触です。

新機能の提案まで

私が日本のお城が好きなのでお城に関するアプリが作りたいと以前からずっと思っていました。
しかし、なかなか機能は増えずな状態がずっと続いていました。
v1.3.0あたりからどんな機能があるといいかな?
どんな情報があると嬉しいかな?
とChatGPTに相談しながら作っています。
個人開発アプリだと相談相手がいるとなんか楽しいですね。
もちろん新機能の提案も大変助かっております。


ということで、個人開発とAIは大変相性がいいのではと思っています。
これからもAIと個人アプリ開発を楽しみたいと思います!

城Naviも宜しくお願いしますー!
alljapanacastle.qkuronekop.dev

【Flutter】個人開発の技術選定

こんにちは。
くろねこです。

私の個人アプリ「城Navi」の技術について書きたいと思います。

フロントはFlutterというフレームワークを使っています。

今回は、城Naviを開発するにあたって、なぜFlutterを選んだのか、そしてバックエンドなどにどんな技術を選んだのかについて書いてみたいと思います。

個人開発では、限られた時間の中で開発を進める必要があります。

そのため、

  • できるだけ開発コストを抑えたい
  • AndroidとiOSの両方に対応したい
  • 一人でもメンテナンスしやすい構成にしたい
  • 新しい機能を追加しやすくしたい

といったことを考えながら技術を選定しました。

城Naviでは、現在以下のような技術を使っています。

項目 技術
フロントエンド Flutter
バックエンド Supabase
データベース PostgreSQL
対応プラットフォーム Android / iOS
公開状況 Android公開済み / iOS準備中
ソースコード管理 Git / GitHub

Flutter

まず、フロントエンドにはFlutterを採用しました。

Flutterを選んだ一番の理由は、1つのコードベースでAndroidとiOSの両方に対応できることです。

個人開発なので、Android用とiOS用に別々のアプリを開発するのは、できるだけ避けたいと考えていました。

FlutterならDartでコードを書きながら、Android・iOSの両方に対応できます。

また、個人的にFlutterを使った開発経験があったことも大きな理由です。

「新しい技術を勉強すること」よりも、「実際にアプリを完成させてリリースすること」を優先しました。

Supabase

バックエンドにはSupabaseを採用しました。

Supabaseを選んだ理由は、データベースを比較的簡単に用意できることです。

城Naviでは、お城の情報やユーザーが登録した情報などをデータベースに保存しています。

SupabaseではPostgreSQLを利用できるため、SQLを使ってデータを扱える点も魅力でした。

個人開発では、サーバーを自分で構築して管理するよりも、こういったBaaSを利用して、アプリそのものの開発に時間を使いたいと考えています。

Android / iOS

城NaviはAndroid版を先に公開しており、iOS版についても公開に向けて準備を進めています。

Flutterを採用したことで、基本的には同じコードを利用しながら両方のプラットフォームに対応しています。

もちろん、完全に同じコードだけで済むわけではありません。

プラットフォーム固有の処理が必要になることもありますし、AndroidとiOSで挙動が異なる部分もあります。

それでも、個人開発で2つのプラットフォームに対応するという意味では、Flutterはかなり強力だと感じています。

個人開発では「作り切れるか」を重視する

今回の技術選定で一番重視したのは、自分一人で開発を続けられるかどうかです。

どれだけ高機能な技術でも、開発や運用が複雑になってしまえば、個人開発では負担になってしまいます。

そのため城Naviでは、

「自分が使い慣れていること」

「開発をスピードアップできること」

「できるだけ運用の手間を減らせること」

を意識して技術を選びました。

これから城Naviに機能を追加していく中で、技術構成が変わることもあると思います。

そのときは、またこのブログで紹介していきたいと思います。

play.google.com

【Flutter】私の考えた最強の構成

あけましておめでとうございます。
新年一発目のブログです。
毎年言ってるけど今年こそアウトプット頑張る。
最近年のせいか、インプットもできなくなってきましたね。。。
言い訳になっちゃうけど、子供ができてからこっちのインプットがなかなかできなくなってきておりますね。
何か小さいことでもいいから新しい事が始められるといいなぁ。

さて、今回のタイトルは「私の考えた最高の構成」なんですが、今作っている個人開発アプリのpubspec.yamlを公開したいと思います。

pubspec.yaml

name: kai_memo
description: "A new Flutter project."
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: ^3.9.2

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.8
  flutter_riverpod: ^3.1.0
  go_router: ^17.0.1
  firebase_core: ^4.3.0
  cloud_firestore: ^6.1.1
  firebase_auth: ^6.1.3
  freezed: ^3.2.3
  freezed_annotation: ^3.1.0
  riverpod_annotation: ^4.0.0
  json_annotation: ^4.9.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^5.0.0
  build_runner: ^2.10.4
  json_serializable: ^6.11.2
  riverpod_generator: ^4.0.0+1
  go_router_builder: ^4.1.3

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
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

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/to/resolution-aware-images

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/to/asset-from-package

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/to/font-from-package

flutterバージョンは3.38.5を使っています。
まだ作っている途中なので今後変わっていく可能性はありますが、一旦こんな感じで作り始めようかと思っています。
実装完了したらコードも公開したいなと思いますし、作成途中の状況とかもここで報告できたらいいなと思っていますので、よかったら追いかけてみてください。
flutter使ってみたいなと思っている方の入門編としていいかなと思います。

なるべく難しいコードを書かないようにしたいが私のモットーでありますので、読みやすいコードを目指していきたいと思います!

それでは本年もよろしくお願い致します。

Gemini CLIにアプリ作ってもらいました!

こんにちは。
今日はGemini CLIにアプリを作ってもらった話をしようかと思います。

まずはGemini CLIのインストール。
Gemini CLIについてはこちらの方の記事を参考にインストールしました。

zenn.dev

ターミナル上で対話型で使って行きます。

最初に、私のPCにない開発環境を作ってもらおうとしたのですが、その環境を作る為のスクリプトが対話型だと難しいみたいです。

flutterの環境は私のPCに既にあったので、flutterでアプリを作ってもらうことにしました。

次にこんなプロンプトでアプリを作ってもらいました。

flutterでゲームを作ってほしいです。flameを使用してください。バージョンは現時点で最新にしてほしいです。ランダムに表示された1〜
  25までの数字を順番にタップして消していくミニゲームがほしいです。

と、お願いしてみたところ、一発で結構それなりのものを作ってくれました。

プロジェクトの作成からファイルの編集までやってくれます。

Geminiたんにflutter runコマンドを使われると、対話ができなくなるので次の入力ができなくて困ってしまうのですが、これは何かやり方があるのだろうか。。。?

作成してもらったアプリを起動して、実際にプレイしつつUIをちょっと手直ししてもらったりして完成したものがこちらです。

私は1つもプログラムを書いていません。

github.com

そして、出来上がったゲームはこちらです。

ぜひ遊んでみてください。

qkuronekop.pussycat.jp

1をタップするとゲームスタートです。
1〜25まで順番にタップしていってください。
どうですか。
なかなかですよね。
指示を出すだけでゲームが作れてしまいました。
もっと色々いじって遊んでみようと思います。

CupertinoTabScaffoldとgo router

こんにちは。
CupertinoTabScaffoldとGoRouterの組み合わせでちょっとはまったので、書いておこうと思います。
ちなみに、GoRouter Builderも使っています。

最初に動かなかったコード。

import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';

class CustomTabView extends StatelessWidget {
  const CustomTabView({
    super.key,
    required this.children,
    required this.navigationShell,
  });

  final StatefulNavigationShell navigationShell;
  final List<Widget> children;

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      tabBar: CupertinoTabBar(
        items: const [
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.home),
            label: 'ホーム',
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.calendar),
            label: '履歴',
          ),
        ],
      ),
      tabBuilder: (context, index) {
        return CupertinoTabView(
          builder: (context) {
            return children[index];
          },
        );
      },
    );
  }
}

次に動いたコード。

import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';

class CustomTabView extends StatelessWidget {
  const CustomTabView({
    super.key,
    required this.children,
    required this.navigationShell,
  });

  final StatefulNavigationShell navigationShell;
  final List<Widget> children;

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      key: ValueKey(navigationShell.currentIndex),
      tabBar: CupertinoTabBar(
        onTap: (index) {
          navigationShell.goBranch(index);
        },
        currentIndex: navigationShell.currentIndex,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.home),
            label: 'ホーム',
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.calendar),
            label: '履歴',
          ),
        ],
      ),
      tabBuilder: (context, index) {
        return CupertinoTabView(
          builder: (context) {
            return children[index];
          },
        );
      },
    );
  }
}

api.flutter.dev

ここみて実装したのですが、動かずonTapの存在に気づいてなんとか動かすことができました。
CupertinoTabScaffold+GoRouter使いた方はぜひ参考にしてみてくださいー!

iosのuniversal linkが動かなかった時の話

こんにちは。
先日、お仕事でuniversal linkについて調べていた時のことでした。
flutterアプリにuniversal linkを導入しようと試みたのですが、どうにも動かなくて3日はまってしまいました。

docs.flutter.dev

flutterにuniversal linkを導入する手順がここに書かれています。

apple-app-site-associationはfirebase hostingにホストしていました。

branch.io

このサービスを使うと、apple-app-site-associationが登録されたかどうかはわかります。
ここに登録されたことは確認済みでした。

動かなかった原因は2つあります。
まず、apple-app-site-associationをホストしたドメインと同じドメインから遷移させようとしていたことです。
これはindexが開いてしまい、うまくアプリに飛んでいかなかったです。

もう1つは、Capabilityを追加する環境を間違えていたことです。
何も考えずにXcodeからAssociated Domainsを追加していたのですが、Profileにしか追加していなかったようです。
debugビルドで確認していたので、Associated Domainsの設定が効いていなかったようです。

docs.flutter.dev この画像と同じようにALLでつけないといけなかったんですね。

そんなこんなでやっと動きました。

しかし、今回の要件ではリダイレクトで使いたいということでした。
リダイレクトを試したみたところ、すんなりアプリに遷移できず結局使うことはなかったです。
そんなこんなで検証に3日もついやしちゃいました。