見出し画像

【Flutter】画面より大きいサイズのウィジェットをスクロールと拡大縮小できるようにする

画像1

InteractiveViewerというウィジェットを使えば簡単に実装することができます。

まずは、白黒模様を作成します。

class FirstPage extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text('InteractiveViewer'),
       centerTitle: true,
     ),
     body: buildPlaid(),
   );
 }

 Widget buildPlaid() {
   double size = 150;

   List<Widget> _list = [];
   List<Widget> _listCache = [];

   for(int i = 0; i < 5; i++) {
     for(int j = 0; j < 5; j++) {
       _listCache.add(
         Container(
           width: size,
           height: size,
           color: blackOrWhite(i, j),
         )
       );
     }
     _list.add(Row(children: _listCache,));
     _listCache = [];
   }

   return Column(
     children: _list,
   );
 }

 Color blackOrWhite(i, j) {
   if((i % 2 == 0 && j % 2 == 0) || (i % 2 == 1 && j % 2 == 1)) {
     return Colors.black;
   } else {
     return Colors.white;
   }
 }
}

画像2

このままだと画面サイズを超えているので、エラーが出てしまいます。

そこでInteractiveViewerでラップし、constrainedプロパティをfalseに設定します。

body: InteractiveViewer(
 constrained: false,
 child: buildPlaid(),
),

そうすれば、ページの最初に貼っているgifにように、画面に合わせてスクロールしたり拡大縮小できるようになります。


この記事が気に入ったらサポートをしてみませんか?