1
0

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 1 year has passed since last update.

【flutter】kIsWebの役割とは!?

Last updated at Posted at 2024-04-18

こんにちは!
今回は最近flutterで作業する際に、知ったkIsWebについて紹介したいと思います。
今回も最後まで読んでいただけたら嬉しいです!

1,kIsWebの役割とは?

FlutterのkIsWebは、FlutterアプリケーションがWebブラウザ上で実行されているかどうかを判別するためのbool型のフラグです。このフラグは、プラットフォーム間でのコードの共有や条件分岐に使用され、開発者が特定のプラットフォームに依存したコードを回避するのに役立ちます。

kIsWebを使用する主な目的は、Web上でのみ必要な機能や設定を適切に実行することです。例えば、モバイルアプリとWebアプリではUIの外観やユーザーエクスペリエンスが異なる場合もあります。kIsWebを使用することで、これらの違いをプログラム内で動的に処理し、ユーザーに最適なエクスペリエンスを提供することができます。

さらに、kIsWebはクロスプラットフォームのコードの可読性と保守性を向上させます。プラットフォーム間でのコードの再利用と共有が容易になるため、開発者は同じコードベースで複数のプラットフォーム向けにアプリを構築することができます。これにより、開発時間の短縮と効率の向上が実現されます。

2,kIsWebの使い方

kIsWebの使い方とその具体的なコード内での条件分岐の例、そしてkIsWebを使ってWeb専用の機能を実装する方法について紹介します。
kIsWebはFlutterのfoundationパッケージに含まれています。これを使うには、まずfoundationパッケージをインポートする必要があります。

import 'package:flutter/foundation.dart';

以下のようにkIsWebを使用してWeb上での実行を確認できます。

if (kIsWeb) {
  // Web上での実行時の処理
} else {
  // Web以外での実行時の処理
}

実際のコード

if (kIsWeb) ...[
              Container(
                height: 100,
                width: 250,
                decoration: BoxDecoration(
                  color: Colors.blue,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Center(
                  child: Text(
                    "これはweb側です",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                    ),
                  ),
                ),
              )
            ] else ...[
              Container(
                height: 100,
                width: 250,
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Center(
                  child: Text(
                    "これはmobile側です",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: Colors.white,
                    ),
                  ),
                ),
              )
            ]

web表示
スクリーンショット 2024-04-18 10.22.53.png

mobile表示
スクリーンショット 2024-04-18 10.22.34.png

終わりに

今回の記事は以上になります。
今回も最後まで読んでいただきありがとうございました!
では、また次の記事で〜!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?