How to use AnimatedModalBarrier widget in flutter?

AnimatedModalBarrier widget is a modal barrier that prevents user interaction with widgets behind it and can be configured with an animated color. This barrier, rendered behind each route, usually darkens the underlying page and prevents interaction with it. It functions similarly to the standard ModalBarrier but uses an animated color instead of a single static color.

Constructor

The constructor of the AnimatedModalBarrier widget gives an idea of its functionalities and is shown below:

AnimatedModalBarrier(
{Key? key, 
required Animation<Color?> color,
bool dismissible = true, 
String? semanticsLabel,
bool? barrierSemanticsDismissible, 
VoidCallback? onDismiss, 
ValueNotifier<EdgeInsets>? clipDetailsNotifier, 
String? semanticsOnTapHint})

Properties of AnimatedModalBarrier widget

barrierSemanticsDismissible: Gives a Boolean value on whether the modal barrier semantics are included in the semantics tree.
clipDetailsNotifier: Contains a value of type EdgeInsets that specifies how the SemanticsNode.rect of the widget should be clipped.
color:If non-null, fill the barrier with this color.
dismissible:Gives a Boolean value on whether touching the barrier will pop the current route off the Navigator.
hashCode:The hash code for this object.
key:Controls how one widget replaces another widget in the tree.
listenable:The Listenable to which this widget is listening.
onDismiss:Called when the barrier is being dismissed.
runtimeType:A representation of the runtime type of the object.
semanticsLabel:Semantics label used for the barrier if it is dismissible.
semanticsOnTapHint:This hint text instructs users what they are able to do when they tap on the ModalBarrier.

Methods Provided in an AnimatedModalBarrier widget

build():Override this method to build widgets that depend on the state of the listenable (e.g., the current value of the animation).
createElement():Creates a StatefulElement to manage this widget’s location in the tree.
createState():Subclasses typically do not override this method.
debugDescribeChildren():Returns a list of DiagnosticsNode objects describing this node’s children.
debugFillProperties():Add additional properties associated with the node.
noSuchMethod():Invoked when a nonexistent method or property is accessed.
toDiagnosticsNode():Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep.
toString():A string representation of this object.
toStringDeep():Returns a string representation of this node and its descendants.
toStringShallow():Returns a one-line detailed description of the object.
toStringShort():A short, textual description of this widget.

Using AnimatedModalBarrier widget

Here is an example of how to create the animation. First, use ColorTween to define the start and end colors. Then, set the duration of the animation in the AnimationController. To create the Animation<Color>, call the animate method of ColorTween and pass the controller as an argument. Finally, use the Animation<Color> as the color argument for AnimatedModalBarrier.

  class _AnimatedModalBarrierAppState extends State<_AnimatedModalBarrierApp> with SingleTickerProviderStateMixin {
    late Widget _animatedModalBarrier;
  
    late AnimationController _animationController;
    late Animation<Color?> _colorTweenAnimation;
  
    @override
    void initState() {
      ColorTween  _colorTween = ColorTween(
        begin: Color.fromARGB(100, 255, 255, 255),
        end: Color.fromARGB(100, 127, 127, 127),
      );
  
      _animationController = AnimationController(
          vsync: this,
          duration: const Duration(seconds: 3)
      );
      _colorTweenAnimation = _colorTween.animate(_animationController);
  
      _animatedModalBarrier = AnimatedModalBarrier(
        color: _colorTweenAnimation
      );
  
      super.initState();
    }
  }

Since this widget prevents user interaction with widgets behind it, the simplest way to implement it is by using a Stack. Place the widgets that should have their interactions disabled before the widget in the stack. In the following example, interactions with the RaisedButton are disabled.

  Stack(
    alignment: AlignmentDirectional.center,
    children: <Widget>[
      RaisedButton(
        child: Text('Button')
      ),
      _animatedModalBarrier
    ],
  )

Implemetation of AnimatedModalBarrier widget

  import 'dart:async';
  import 'package:flutter/material.dart';
  
  void main() => runApp(MyApp());
  
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Flutter Tutorial by Woolha.com',
        home: _AnimatedModalBarrierApp(),
      );
    }
  }
  
  class _AnimatedModalBarrierApp extends StatefulWidget {
    @override
    State<StatefulWidget> createState() {
      return _AnimatedModalBarrierAppState();
    }
  }
  
  class _AnimatedModalBarrierAppState extends State<_AnimatedModalBarrierApp> with SingleTickerProviderStateMixin {
    bool _isLoading = false;
    late Widget _animatedModalBarrier;
  
    late AnimationController _animationController;
    late Animation<Color?> _colorTweenAnimation;
  
    @override
    void initState() {
      ColorTween  _colorTween = ColorTween(
        begin: Color.fromARGB(100, 255, 255, 255),
        end: Color.fromARGB(100, 127, 127, 127),
      );
  
      _animationController = AnimationController(
          vsync: this,
          duration: const Duration(seconds: 3)
      );
      _colorTweenAnimation = _colorTween.animate(_animationController);
  
      _animatedModalBarrier = AnimatedModalBarrier(
        color: _colorTweenAnimation,
        dismissible: true,
      );
  
      super.initState();
    }
  
    List<Widget> buildWidgetList(BuildContext context) {
      List<Widget> widgets = <Widget>[
        RaisedButton(
          child: Text('Button'),
          onPressed: () {
            setState(() {
              _isLoading = true;
            });
  
            _animationController.reset();
            _animationController.forward();
  
            Scaffold.of(context).showSnackBar(
              SnackBar(content: Text('Button is pressed'))
            );
  
            Future.delayed(const Duration(seconds: 5), () {
              setState(() {
                _isLoading = false;
              });
            });
          },
        ),
      ];
  
      if (_isLoading) {
        widgets.add(_animatedModalBarrier);
      }
  
      return widgets;
    }
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Woolha.com Flutter Tutorial'),
        ),
        body: Builder(
          builder: (context) => Center(
            child: Padding(
              padding: EdgeInsets.all(15.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Container(
                    height: 100.0,
                    width: 250.0,
                    // alignment: FractionalOffset.center,
                    child: new Stack(
                      alignment: AlignmentDirectional.center,
                      children: buildWidgetList(context),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }
  }

Conclusion

So, in this article, we learned how to use the AnimatedModalBarrier widget. You can change and update this Flutter code according to your requirement. I hope you liked reading this.For more such flutter tutorials follow our blog.Each blog is crafted with love by the FlutterCurious Team.

Wanna Level up Your Flutter game? Then check out our ebook The Complete Guide to Flutter Developement where we teach you how to build production grade cross platform apps from scratch.Do check it out to completely Master Flutter framework from basic to advanced level.

Also Read

How to use Filled Button in flutter

Leave a comment