見出し画像

Flutterで画面の向きによってUIを更新する

初めましてblueです。

現在、ITベンチャー企業でWEBキャンペーンシステムの運用並びに要件定義、ECサイトの開発を行なっています。

今回は、Flutterで画面の向きによってUIを更新する方法について記事にしてみました!

使用するメソッド

実装コード

OrientationBuilder(
       builder: (context, orientation) {
         print(orientation);
         return GridView.count(
           crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
           children: List.generate(10, (index) {
             return Center(
               child: Text(
                 '$index',
                 style: const TextStyle(fontSize: 50),
               ),
             );
           }),
         );
       },
     ),

OrientationBuilderでWidgetを生成。
orientationの値によって、2列表示にしたり、3列表示にしたりします。

縦向きの場合
Orientation.portrait

横向きの場合
Orientation.landscape

全体コード

import 'package:flutter/material.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);

 @override
 Widget build(BuildContext context) {
   const appTitle = 'Orientation';

   return const MaterialApp(
     title: appTitle,
     home: OrientationList(
       title: appTitle,
     ),
   );
 }
}

class OrientationList extends StatelessWidget {
 final String title;

 const OrientationList({Key? key, required this.title}) : super(key: key);
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(title: Text(title)),
     body: OrientationBuilder(
       builder: (context, orientation) {
         return GridView.count(
           crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
           children: List.generate(10, (index) {
             return Center(
               child: Text(
                 '$index',
                 style: const TextStyle(fontSize: 50),
               ),
             );
           }),
         );
       },
     ),
   );
 }
}

実装画面

縦向き

画像1

横向き

画像2


良かったらサポートしていただけると嬉しいです!