Flutter Webをスマホ画面に適応させる

2023年2月12日

開発環境
OS:Windows 10
SDK:VS Code + flutter 3.3.10

概要

PC画面とスマホ画面、2画面分のWidgetを用意し、使い分ける

Flutter WebはPCからアクセスするとは限らない

FlutterでAndroidアプリやiOSアプリを作るならスマートフォン利用前提になるので

画面構成は基本的には縦配置のみの考慮でいいはずです。

ですが、Flutter Webの場合、ブラウザでアクセスするため、

PCとスマホ、どちらからでも利用できるよう想定しなれけばいけません。

つまり横配置を前提としてPC画面用Widget、横配置を前提としたスマホ用Wiget、

2パターンの画面構成に対応したWidgetを用意する必要があります。

PC用Widgetとスマホ用Widget

まずはPC用とスマホ用、それぞれの画面構成を作成します。

それぞれWidgetを関数化しておくと便利です。

(PC用Wigetの作成例)

  Widget _createPCView(BuildContext context)  {
    return Align(
      alignment: Alignment.topLeft,
      child: Container(
        width: 250,
        height: 200,
        margin: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: Colors.yellow,
          border: Border.all(color: Colors.grey, width: 1),
          borderRadius: BorderRadius.circular(5.0)
        ),
        child: Column(
          children: [
           ・・・
          ],)
      ),
    );
  }

(スマホ用Widgetの作成例)

   Widget _createMobileView(BuildContext context)  {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        width: double.infinity,
        height: 80,
        margin: const EdgeInsets.only(bottom: adHeight),
        decoration: BoxDecoration(
          color: Colors.yellow,
          border: Border.all(color: Colors.grey, width: 1),
          borderRadius: BorderRadius.circular(5.0)
        ),
        child: Column(
          children: [
           ・・・
          ],)
      ),
    );
  }

画面サイズでWidget使い分ける

あとは画面サイズを取得し、サイズによってWidgetを使い分けます。

画面サイズの取得には、MediaQuery.of(context).sizeを使用します。

またPCとスマートフォンの画面サイズの境界値は400とします。

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        alignment: Alignment.center,
        child: screenSize.width > screenWidth? _createPCView(context) : _createMobileView(context)
      )
    );
  }

これでPCとスマートフォンどちらにも対応できます。

実際にWeb画面をスマートフォンとPCで表示すると以下のようになります。

https://messageexchanger-fa3e1.web.app