Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanded widget with minimum height in Flutter

Tags:

flutter

widget

Context of my problem: Expanded widget shrink its child widgets to zero height if required and ignore its children constraints.

Goal: preventing an expanded widget from shrinking to less than its child size so that its widgets won't get destroyed.

In addition, I need the widget to take all available space and expand its child.

Side note: Container is used for allocating height space to make expanded react to the change in space

Here is the code:

import 'package:flutter/material.dart';

class MainScreen extends StatelessWidget {
  const MainScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Expanded(
            child: Card(
              color: Colors.blueAccent,
              child: LimitedBox(
                maxHeight: 200,
                child: Text(
                  'Test dummy text Test dummy text Test dummy text Test dummy text Test dummy text Test dummy text Test dummy text Test dummy text Test dummy text Test dummy text ',
                  style: TextStyle(fontSize: 60, color: Colors.black),
                ),
              ),
            ),
          ),
          Container(
            color: Colors.amberAccent,
            height: 105,
            width: 200,
          )
        ],
      ),
    );
  }
}

This is the unwanted current output:

Expanded behavior that is required

Expanded normal behavior:

Shrinking behavior that is NOT required

like image 293
Aziz Avatar asked Jun 30 '20 08:06

Aziz


1 Answers

Use Flexible widget and add the Container with min-height, The size of blue container will increase as the text increases.

 Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView( 
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Flexible(
              child: Container(
                constraints: BoxConstraints(
                    minHeight: 200, minWidth: double.infinity),
                child: Card(
                  color: Colors.blueAccent,
                  child: Text(
                    'Sample Text',
                    style: TextStyle(fontSize: 60, color: Colors.black),
                  ),
                ),
              ),
            ),
            Container(
              color: Colors.amberAccent,
              height: 105,
              width: 200,
            )
          ],
        ),
      )
  ),

Output:

enter image description here

like image 96
Jitesh Mohite Avatar answered Oct 18 '22 23:10

Jitesh Mohite