10
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

メモ:flutterで自動的に閉じるシンプルなoverlay dialogをだす

Posted at
  • シンプルでいいけど、animationでぬるっと出てきて自動的に閉じてくれるoverlayな表示を出すための実装。

overlay dialog widgetの実装

  • 以下がwidgetのコード。
overlay_dialog.dart
import 'package:flutter/material.dart';

class OverlayDialog extends StatefulWidget {
  OverlayDialog({Key key, this.message}):super(key:key);

  final String message;

  @override
  State<StatefulWidget> createState() => OverlayDialogState();
}

class OverlayDialogState extends State<OverlayDialog>
    with SingleTickerProviderStateMixin {
  AnimationController controller;
  Animation<double> opacityAnimation;
  Animation<double> scaleAnimatoin;

  @override
  void initState() {
    super.initState();

    controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 450));
    opacityAnimation = Tween<double>(begin: 0.0, end: 0.4).animate(
        CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn));
    scaleAnimatoin =
        CurvedAnimation(parent: controller, curve: Curves.elasticInOut);

    controller.addListener(() {
      setState(() {});
    });

    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black.withOpacity(opacityAnimation.value),
      child: Center(
        child: ScaleTransition(
          scale: scaleAnimatoin,
          child: Container(
            decoration: ShapeDecoration(
                color: Colors.white,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.0))),
            child: Padding(
              padding: const EdgeInsets.all(50.0),
              child: Text(widget.message),
            ),
          ),
        ),
      ),
    );
  }
}

widgetのopen/closeの実装

  • overlay dialog wigetを開き、1秒後に閉じるコード。今回はボタンをおした時にoverlay表示を出すので、onPressedのfunctionに入れてある。
  void _onPressed() {
    setState(() {
      var _overlayEntry = OverlayEntry(
        builder: (BuildContext context) {
          return OverlayDialog(message: "open!");
        },
      );
      Navigator.of(context).overlay.insert(_overlayEntry);
      Timer(Duration(seconds: 1), () => _overlayEntry.remove());
    });
  }

10
14
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
10
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?