この記事は、「Flutter Advent Calendar 2021」に投稿した「Flutter on the WebをFirebase Hostingで公開した」の一部となります。
レスポンシブ、デスクトップとスマホで出し分ける
デスクトップの時は左側に選択メニューを出しっぱなしに、スマホの時はドロワーメニューで出し入れできるようにしたいと考えて調べたところ、Flutterの公式ギャラリー自体がそれらしき実装をしていました。
公式ギャラリーにある以下のコードをそのまま引っぱってきて使っています。
adaptive_breakpoints
のウインドウタイプを見ているので厳密には、デバイスの種類ではなく画面幅です。
import 'package:adaptive_breakpoints/adaptive_breakpoints.dart';
import 'package:flutter/material.dart';
/// Returns a boolean value whether the window is considered medium or large size.
///
/// Used to build adaptive and responsive layouts.
bool isDisplayDesktop(BuildContext context) =>
getWindowType(context) >= AdaptiveWindowType.medium;
/// Returns boolean value whether the window is considered medium size.
///
/// Used to build adaptive and responsive layouts.
bool isDisplaySmallDesktop(BuildContext context) {
return getWindowType(context) == AdaptiveWindowType.medium;
}
以下のように、Drawer
とScaffold
の組み合わせを画面幅に応じて出し分けています。
frame_widget.dart
final isDesktop = isDisplayDesktop(context);
return Title(
color: Colors.white,
title: mytitle,
child: isDesktop
? Row(children: [
Drawer(
child: HorsesWidget(
listView: true,
horseListJsonData: horseListJsonData,
)),
const VerticalDivider(width: 1),
Expanded(
child: Scaffold(
appBar: AdaptiveAppBar(
pagepath: pagepath,
title: mytitle,
isDesktop: true,
),
body: Column(children: [
Expanded(flex: 1, child: body),
SizedBox(height: adHeight)
])))
])
: Scaffold(
appBar: AdaptiveAppBar(pagepath: pagepath, title: mytitle),
drawer: Drawer(
child: HorsesWidget(
listView: true, horseListJsonData: horseListJsonData)),
body: Column(children: [
Expanded(flex: 1, child: body),
SizedBox(height: adHeight)
])));
以上です。