LoginSignup
6
7

More than 3 years have passed since last update.

showModalBottomSheetで角が丸いContainerを表示する【Flutter】

Posted at

はじめに

showModalBottomSheet()というメソッドを利用することで、「下からニョキっと出てくるウインドウ」のようなものを作ることができる。

今回は、それを使って「角が丸いContainer」を表示する。
以下の画像のような感じ。

image.png

上辺の両端を見ていただけたらお分かりの通り、角が丸い。
角を丸くするためにはRoundedRectangleBorderウィジェットを利用するのだが、普通に使うとContainerとの相性が悪いようである。
それについては、後で解説する。

コード

では早速、コードを全文載せておく。

main.dart
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を指定して、赤色にしようとしている。
実行すると、こうなる。

image.png

角が四角い!!

これはガッカリした。
どうやら角を丸くしつつ、色を変更するためには、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,
                  );
                });

実行すると、こうなる。

image.png

これで一件落着!

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7