はじめに
showModalBottomSheet()というメソッドを利用することで、「下からニョキっと出てくるウインドウ」のようなものを作ることができる。
今回は、それを使って「角が丸いContainer」を表示する。
以下の画像のような感じ。
上辺の両端を見ていただけたらお分かりの通り、角が丸い。
角を丸くするためにはRoundedRectangleBorderウィジェットを利用するのだが、普通に使うとContainerとの相性が悪いようである。
それについては、後で解説する。
コード
では早速、コードを全文載せておく。
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: MyApp(),
));
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
child: Text('Push'),
onPressed: () {
showModalBottomSheet(
context: context,
isScrollControlled: true, //trueにしないと、Containerのheightが反映されない
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(15)),
),
builder: (BuildContext context) {
return Container(
height: 540,
);
});
},
),
),
);
}
}
showModalBottomSheetのプロパティとして、isScrollControlledとshapeを指定している。
それ以外は、いたって単純。
isScrollControlledはtrueに設定しないと、Containerのheight設定が反映されないので、注意。
これで、ボタンを押すと画像のようなウインドウが表示されるアプリができた。
難点
Containerの色を変更したいときはどうすればよいのだろうか。
実はContainer内でcolorプロパティを変更しても、うまくいかない。
試しにContainerウィジェット内をこう書き変えてみてほしい。
return Container(
height: 540,
color: Colors.red,
);
colorプロパティにColors.redを指定して、赤色にしようとしている。
実行すると、こうなる。
角が四角い!!
これはガッカリした。
どうやら角を丸くしつつ、色を変更するためには、ContainerではなくshowModalBottomSheetそのものの引数に渡さないといけないみたい。
というわけで、showModalBottomSheet内をこう書き変えると、うまくいく。
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.red, //これを追加した
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(15)),
),
builder: (BuildContext context) {
return Container(
height: 540,
);
});
実行すると、こうなる。
これで一件落着!