Search code examples
flutternavigation-drawerflutter-webtoolbarflutter-animation

Navigationrail leading/trailing align to left


I have a Navigationrail widget with a button to extend/collapse it. Trailing/leading widgets in one line with NavigationRailDestination when extend=false, but when extend=true trailing/leading widgets always align to center.

Is it possible to align it to the left/right?

My goal: trailing/leading widgets should not change it's positions to center when navigationrail extended.

enter image description here


Solution

  • I found a solution by editing this example: https://api.flutter.dev/flutter/material/NavigationRail/extendedAnimation.html

    Solution: use Animation of NavigationRail

    final Animation<double> animation =
            NavigationRail.extendedAnimation(context);
    

    and then change the width/padding according to it with lerpDouble function:

    padding: EdgeInsets.only(
            right: lerpDouble(0, 200, animation.value)!,
            bottom: 30,
          ),
    

    Full working code:

    import 'dart:ui';
    import 'package:flutter/material.dart';
    
    class NavigationRailMenuButton extends StatelessWidget {
    
       const NavigationRailMenuButton({super.key, this.onPressed});
       final VoidCallback? onPressed;
       
       @override
       Widget build(BuildContext context) {
        final Animation<double> animation =
            NavigationRail.extendedAnimation(context);
        return AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget? child) {
            return Container(
              padding: EdgeInsets.only(
                right: lerpDouble(0, 200, animation.value)!,
              ),
              child: IconButton(
                icon: const Icon(Icons.menu),
                iconSize: 32,
                onPressed: onPressed,
              ),
            );
          },
        );
      }
    }