devT
devT

Reputation: 105

How can i display a widget for a sec only, Then hide it again in Flutter

I want to display a widget only if i press a button, then after a second it disappear

I'm trying to do it with Opacity Widget something like this:

double _woofOp = 0.0;

  void hideImg(){
    Duration(seconds: 1);
    setState(() {
      _woofOp = 0.0;
    });
  }
  void playAudio() {
    setState(() {
      _woofOp = 1.0;
      playBark.play('DogWoof.mp3');
    });
    hideImg();
  }

and the widget:

Opacity(
        opacity: _woofOp,
        child: Image.asset('images/woof-png.png',
        width: 80.0,
        ),
)

but by using it nothing happens,(but audio works which is in same function) any idea why?

or any idea how can i do that using another ways? I'm just a learner. Thank you

Upvotes: 2

Views: 2581

Answers (1)

konstantin_doncov
konstantin_doncov

Reputation: 2879

You can do this using OverlayEntry.

You should call this method from your widget:

 static void showToast({
    @required BuildContext context,
  }) {

    OverlayEntry overlayEntry;

    overlayEntry = OverlayEntry(
        builder: (context) => ToastWidget(
        )
    );
    Overlay.of(context).insert(overlayEntry);
    Timer(Duration(seconds: 1), () =>  overlayEntry.remove());

  }

toast_widget.dart:

class ToastWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 100.0,
      width: MediaQuery.of(context).size.width - 20,
      left: 10,

      child: Material(
        color: Colors.blue,
        elevation: 10.0,
        borderRadius: BorderRadius.circular(10),
        child: Text('Hello from toast'),
      ),
    );
  }
}

This is very simple implementation without any beautifications like styles or animation, but you can customize it as you want.

Also, you can check this useful guide: https://medium.com/@Mak95/how-to-make-custom-toast-messages-in-flutter-9799ef3239b7

Upvotes: 1

Related Questions