Home > Mobile >  How to dynamically expand a widget by/relative to child dimensions with animation flutter
How to dynamically expand a widget by/relative to child dimensions with animation flutter

Time:05-21

I am trying to expand/animate a container relative to the contained widget dynamic dimensions.

I tried getting the extracting inner widget dimensions by getting its renderbox dimensions. i have this for getting dimensions change

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

typedef void OnWidgetSizeChange(Size size);

class MeasureSizeRenderObject extends RenderProxyBox {
  Size? oldSize;
  final OnWidgetSizeChange onChange;

  MeasureSizeRenderObject(this.onChange);

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

    Size newSize = child!.size;
    if (oldSize == newSize) return;

    oldSize = newSize;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      onChange(newSize);
    });
  }
}

class MeasureSize extends SingleChildRenderObjectWidget {
  final OnWidgetSizeChange onChange;

  const MeasureSize({
    Key? key,
    required this.onChange,
    required Widget child,
  }) : super(key: key, child: child);

  @override
  RenderObject createRenderObject(BuildContext context) {
    print('=============bro we here=======');
    return MeasureSizeRenderObject(onChange);
  }
}

using it like this

...
double _width = 0;
double _height = 0;
...
AnimatedContainerApp(
            width: _width,
            height: _height,
            child: MeasureSize(
                onChange: (size) {
                  print(size.height);
                  setState(() {
                    _height = size.height;
                  });
                },
                child: !isExpanded
                    ? Container(
                        height: 200,
                        width: double.Infinity
                        )
                    : Container(
                        height: 400,
                        width: double.Infinity
                        )),
          ),

with AnimatedContainerApp being a simple AnimatedContainer widget.

I am unable to trigger and update dimensions for the animation. also if the is a better way to achive that I am open for it.

CodePudding user response:

You can use AnimatedSize widget https://api.flutter.dev/flutter/widgets/AnimatedSize-class.html but make sure that it will animate only one side. or else you can check https://stackoverflow.com/a/59133346/19165706 solution here.

  • Related