Home > Software engineering >  Flutter: How Do I Set a Container's Width to a Calculated Value?
Flutter: How Do I Set a Container's Width to a Calculated Value?

Time:07-23

I have a widget that gets a decimal as a property, and I want to use that decimal to calculate the width of a Container. Here's a simplified version of my code:

class MyWidget extends StatelessWidget {
  final double percent;
  const MyWidget({
    Key? key,
    required this.percent,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: percent * double.infinity, //<-- Here
      height: 5,
    );
  }
}

The result of percent * double.infinity never amounts to more than a few pixels. I have also tried hard-coding it to something like:

width: percent * 100, //<-- Here

But that doesn't render more than a few pixels either. My assumption is that the Container isn't getting an actual width. I've tried making this a StatefulWidget and setting the width value in initState() but that doesn't seem to help either:

var width = 5.0;
@override
void initState() {
  width = widget.airport.percent ?? 0.0 * 100.0;
  super.initState();
}

How can I calculate a width value on-the-fly like this?

CodePudding user response:

You can try using LayoutBuilder for your widget: it will give you context and BoxConstraints as arguments and you can get the max width available for the widget in that BoxConstraints by using: constraints.maxWidth or height using constraints.maxHeight

here is a sample code:

class MyWidget extends StatelessWidget {
  final double percent;
  const MyWidget({
    Key? key,
    required this.percent,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (ctx, constraints){
        return Cointainer(
         width: percent * constraints.maxWidth, 
         height: 5, // also you can use constraints.maxHeight to calculate height
        );
      }
    );
  }
}
  • Related