How to use ConstrainedBox in Flutter

In this Google flutter code example we are going to learn how to use ConstrainedBox in Flutter.

You can copy and adopt this source code example to your android project without reinventing the wheel.

The comments on the code provide more detailed explanation

The code is based on flutter version 1 and 2.

main.dart (App entry point)

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter AspectRatio Widget',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: BasicAspectRatio(),
    );
  }
}

constrainedbox.dart

import 'package:flutter/material.dart';

class BasicConstrainedBox extends StatelessWidget {
  //A widget that imposes additional constraints on its child.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("ConstrainedBox Widget")),
      body: Center(
        child: ConstrainedBox(
          //set constraints property
          //BoxConstraints() : Creates box constraints with the given constraints.
          //BoxConstraints.expand(): Creates box constraints that expand to fill another box constraints.
          //BoxConstraints.tight(): Creates box constraints that is respected only by the given size.
          //BoxConstraints.loose(): Creates box constraints that forbid sizes larger than the given size.
          //BoxConstraints.tightFor(): Creates box constraints that require the given width or height.
          //BoxConstraints.tightForFinite(): Creates box constraints that require the given width or height, except if they are infinite.
          //here, our container, is 150x150, but we constrained it to 60x60
          constraints: BoxConstraints(maxHeight: 60.0, maxWidth: 60.0),
          child: Container(height: 150.0, width: 150.0, color: Colors.red),
        ),
      ),
    );
  }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment