やりたいこと
Flutter_webで作成したWebアプリケーションをレスポンシブに対応させる
というよりPC、タブレット、モバイル端末の判定をする
お急ぎの方(ソースコード)
- クラス定義
device_type.dart
import 'package:flutter/material.dart';
import 'dart:html' as html;
const String PC = "PC";
const String TABLET = "Tablet";
const String MOBILE = "Mobile";
class DeviceType {
// モバイル端末かどうかiPhone,androidスマートフォン
static bool isMobileUserAgent() {
String userAgent = html.window.navigator.userAgent.toLowerCase();
return userAgent.contains('iphone') ||
(userAgent.contains('android') && userAgent.contains('mobile'));
}
// タブレット端末かどうかiPadやAndroidタブレット
static bool isTabletUserAgent() {
String userAgent = html.window.navigator.userAgent.toLowerCase();
return userAgent.contains('ipad') || userAgent.contains('macintosh')
// androidタブレット
userAgent.contains('linux; android') ||
// windowsタブレット
(userAgent.contains('windows') && userAgent.contains('touch'));
}
// Windowsタブレットかどうか
static bool isWindowsTablet() {
String userAgent = html.window.navigator.userAgent.toLowerCase();
return (userAgent.contains('windows') && userAgent.contains('touch')) ||
(userAgent.contains('windows') && userAgent.contains('tablet'));
}
// タッチ可能かどうか
static bool isTouchScreen() {
return html.window.navigator.maxTouchPoints > 0;
}
static String detectDeviceType(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
if (isMobileUserAgent() || screenWidth < 430) {// お好みで
return MOBILE; // モバイルデバイス
} else if (isTabletUserAgent() || screenWidth <= 1024)) {// お好みで
if (isTouchScreen() || isTabletUserAgent()) {
return TABLET; // タブレット
}
return PC; // タブレットでもタッチスクリーンがない場合PCとみなす
} else if (isWindowsTablet()) {
return TABLET; // Windowsタブレット
} else {
return PC; // PC
}
}
}
- 使用方法
device_specific_view.dart
class DeviceSpecificView extends StatelessWidget {
@override
Widget build(BuildContext context) {
String deviceType = DeviceType.detectDeviceType(context);
return Scaffold(
body: getDeviceSpecificView(deviceType),
);
}
// 特定のViewを呼び出すWidget型のメソッド
Widget getDeviceSpecificView(String deviceType) {
switch (deviceType) {
case MOBILE:
return MobileView();
case TABLET:
return TabletView();
case PC:
default:
return PCView();
}
}
}
想定している要件
モバイル端末
- Androidのスマートフォン、iPhoneの2種類
- ユーザーエージェントは以下の表
OS | User Agentに含まれる文字 |
---|---|
iOS | iPhone |
Android | android,mobile |
タブレット
- iPad、Androidのタブレット、Windowsのタブレットの3種類
- タッチが可能
- ユーザーエージェントは以下の表
OS | User Agentに含まれる文字 |
---|---|
ipad | ipad,macintosh |
android | Linux; Android |
windows | Windows ,touch or Windows, tablet等 |
PC
- 上記以外をPCとする
注意事項
すべての端末で動作確認をいしたわけではないので適宜、要件に合わせて設定を変更してください。
また、昨今、UserAgentは削減傾向であるため、そもそもWidthのみでレスポンシブ対応する方が理にかなっているのかもしれません。
参考