Flutter AnimatedModalBarrier Example

AnimatedModalBarrier widget prevents users to interact with its child, which is a widget behind it.

In this AnimatedModalBarrier example, we try showing a barrier that hide the content.

import 'package:flutter/material.dart';

class Homepage extends StatefulWidget {
  const Homepage({Key? key}) : super(key: key);

  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> with SingleTickerProviderStateMixin{
  late AnimationController _controller;
  late Animation<Color?> _color;

  @override
  void initState() {
    ColorTween?  _colorTween = ColorTween(
      begin: null,
      end: Colors.blue.withOpacity(0.25),
    );

    _controller = AnimationController(
        vsync: this,
        duration: const Duration(seconds: 1)
    );
    _color = _colorTween.animate(_controller);

    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
        child: Stack(
          children: [
            Align(
              alignment: Alignment.center,
              child: Container(
                width: 200,
                height: 200,
                color: Colors.green,
                child: Center(child: Text('Content need to hide')),
              ),
            ),
            AnimatedModalBarrier(color: _color)
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            if(_controller.status == AnimationStatus.completed){
              _controller.reverse();
            } else {
              _controller.forward();
            }
          });
        },
        backgroundColor:  Colors.green,
        child: Icon(Icons.highlight_alt_sharp),
      ),
    );
  }
}

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close