Skip to content

Instantly share code, notes, and snippets.

@loic-sharma
Created February 4, 2026 18:37
Show Gist options
  • Select an option

  • Save loic-sharma/3fc50872340be8d52814fe3c886151b9 to your computer and use it in GitHub Desktop.

Select an option

Save loic-sharma/3fc50872340be8d52814fe3c886151b9 to your computer and use it in GitHub Desktop.
SizedBox's layout behavior with incompatible constraints
import 'package:flutter/widgets.dart';
void main() {
final tight_200x200 = BoxConstraints.tight(Size(200, 200));
final tight_100x100 = BoxConstraints.tight(Size(100, 100));
final loose_0x0_to_200x200 = BoxConstraints.loose(Size(200, 200));
// Mimic this example:
//
// SizeBox(
// width: 200,
// height: 200,
// SizedBox(
// width: 100,
// height: 100,
// ),
// ),
//
// This:
// 1. SizedBox#1 creates tight constraints 200x200
// 2. SizedBox#2 attempts to apply additional tight constraints 100x100.
// These are two tight constraints with no overlap, so the additional constraints
// are ignored.
print(tight_200x200.applyAdditionalConstraints(tight_100x100)); // 200x200
// Mimic this example:
//
// SizeBox(
// width: 200,
// height: 200,
// Center(
// child: SizedBox(
// width: 100,
// height: 100,
// ),
// ),
// ),
//
// This:
// 1. SizedBox#1 creates tight constraints 200x200
// 2. Center accepts tight constraints 200x200 and sizes itself 200x200.
// It creates loose constraints 0x0 to 200x200 and passes that down to its child.
// 3. SizedBox#2 attempts to apply additional tight constraints 100x100.
// This _is_ within 0x0 to 200x200, so the resulting constraints are 100x100.
print(loose_0x0_to_200x200.applyAdditionalConstraints(tight_100x100)); // 100x100
}
extension on BoxConstraints {
BoxConstraints applyAdditionalConstraints(BoxConstraints additional) {
// BoxConstraints.enforce respects the given constraints while trying to be
// as close as possible to the additional constraints.
return additional.enforce(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment