見出し画像

はみ出たらスクロールさせる方法

表示要素が画面の縦サイズやContainerなどで指定した領域をはみ出たときにスクロールさせる方法です。

SingleChildScrollViewを使う

スクロールさせたい要素をSingleChildScrollViewでラップするだけです。Containerで高さの制約をつけます。

サンプルコードでは、boxHeight<402の場合はスクロールしますが、boxHeightが402以上の場合はスクロールしません。高さ100のContainerが4つあるので、しきい値は400と思いがちですが、外側のContainerのborder widthが1なので、上下のボーダー分2が加算されしきい値は402になります。

const boxHeight = 300.0;

class MyWidget extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return Center(
     child: Container(
       height: boxHeight,
       margin: EdgeInsets.all(10),
       decoration: BoxDecoration(
         color: Colors.red,
         border: Border.all(
           color: Colors.blue,
           width: 1,
         ),
       ),
       child: Scrollbar(
         isAlwaysShown: false,
         child: SingleChildScrollView(
           child: Column(
             children: <Widget>[
               Container(
                 height: 100,
                 color: Colors.green[50],
               ),
               Container(
                 height: 100,
                 color: Colors.green[100],
               ),
               Container(
                 height: 100,
                 color: Colors.green[200],
               ),
               Container(
                 height: 100,
                 color: Colors.green[300],
               ),
             ],
           ),
         ),
       ),
     ),
   );
 }
}

スクロールバーを表示する

SingleChildScrollViewでスクロールをするようになりますが、スクロールバーは表示されません。スクロールバーが必要であればScrollbarでラップします。
ただし、スクロールバーを常に表示するisAlwaysShownプロパティがバグっていてtrueにするとExceptionが発生します(2020.5.9現在)修正されるまではfalseかisAlwaysShownプロパティを指定しないで使いましょう。

Scrollbar(
  isAlwaysShown: false,
  child: SingleChildScrollView(),
)


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