広告

Flutterラボの

プレミアム会員になる

【Flutter】【Dart】端末サイズからWidgetのサイズを指定する

2020.08.19

端末のサイズデータから画面に表示したいWidgetのサイズを指定したいことってありませんか?しかし、それぞれの端末ごとに分岐させて〇〇pxのように指定してしまうと、とてつもない作業量になります。こちらの記事ではMediaQueryを使用して、端末のサイズを取得しそれぞれのWidgetのサイズを指定していきたいと思います。

サイズを決め打ちで入力した時の問題点

body: Padding(
       padding: const EdgeInsets.all(8.0),
       child: Center(
         child: Column(
           children: [
             Container(
               height: 100,
               color: Colors.blue,
             ),
             Container(
               height: 200,
               color: Colors.green,
             ),
             Container(
               height: 300,
               color: Colors.red,
             ),
           ],
         ),
       ),
     ),

Pixel2の場合(MediaQuery使用前)

画像2

iPhone6sの場合(MediaQuery使用前)

画像1

上のように画面の大きいデバイスだと問題ないのですが、iPhone6sのように画面の小さいデバイスだとエラーが出てしまいます。


MediaQueryをBuild内で使用して変数に代入しておく

Widget build(BuildContext context) {
   final double deviceHeight = MediaQuery.of(context).size.height;
   return Scaffold(
     ...
   );
 }


使用したい場所で画面との割合と計算して変数を呼び出す。

Padding(
       padding: const EdgeInsets.all(8.0),
       child: Center(
         child: Column(
           children: [
             Container(
               height: deviceHeight * 0.1,
               color: Colors.blue,
             ),
             Container(
               height: deviceHeight * 0.3,
               color: Colors.green,
             ),
             Container(
               height: deviceHeight * 0.4,
               color: Colors.red,
             ),
           ],
         ),
       ),
     ),


Pixel2(MediaQuery使用後)

画像4

iPhone6sでは(MediaQuery使用後)

画像3

全体コード

class HomePage extends StatefulWidget {
 HomePage({Key key, this.title}) : super(key: key);

 final String title;

 @override
 _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
 @override
 Widget build(BuildContext context) {
   final double deviceHeight = MediaQuery.of(context).size.height;
   return Scaffold(
     resizeToAvoidBottomPadding: false,
     appBar: AppBar(
       title: Text(widget.title),
     ),
     body: Padding(
       padding: const EdgeInsets.all(8.0),
       child: Center(
         child: Column(
           children: [
             Container(
               height: deviceHeight * 0.1,
               color: Colors.blue,
             ),
             Container(
               height: deviceHeight * 0.3,
               color: Colors.green,
             ),
             Container(
               height: deviceHeight * 0.4,
               color: Colors.red,
             ),
           ],
         ),
       ),
     ),
   );
 }
}
Flutterラボ|動画で学ぶFlutter学習サイト Flutter・Dart・Firebaseに関するアプリ制作の技術を学ぶことができます。プログラミング初心者から経験者まで flutterlabo.tech





Flutterラボ
hatchoutschool
FlutterとNuxtに関する知識を発信しています! 動画で学べる学習サイト『Flutterラボ』と『Nuxtラボ』を運営 Flutterラボ:https://flutterlabo.tech/ 広告のECサイトを開発(https://ec-ad.tech/)