Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanded with max width / height?

Tags:

flutter

dart

I want widgets that has certain size but shrink if available space is too small for them to fit.
Let's say available space is 100px, and each of child widgets are 10px in width.
Say parent's size got smaller to 90px due to resize.
By default, if there are 10 childs, the 10th child will not be rendered as it overflows.
In this case, I want these 10 childs to shrink in even manner so every childs become 9px in width to fit inside parent as whole.
And even if available size is bigger than 100px, they keep their size.
Wonder if there's any way I can achieve this.

        return Expanded(
            child: Row(
                children: [
                    ...List.generate(Navigation().state.length * 2, (index) => index % 2 == 0 ?  Flexible(child: _Tab(index: index ~/ 2, refresh: refresh)) : _Seperator(index: index)),
                    Expanded(child: Container(color: ColorScheme.brightness_0))
                ]
            )
        );
...
    _Tab({ required this.index, required this.refresh }) : super(
        constraints: BoxConstraints(minWidth: 120, maxWidth: 200, minHeight: 35, maxHeight: 35),
...
like image 619
Sombian Avatar asked Sep 20 '25 10:09

Sombian


2 Answers

you need to change Expanded to Flexible

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(appBar: AppBar(), body: Body()),
    );
  }
}

class Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 80,
      color: Colors.green,
      child: Row(
        children: List.generate(10, (i) {
          return Flexible(
            child: Container(
              constraints: BoxConstraints(maxWidth: 10, maxHeight: 10),
              foregroundDecoration: BoxDecoration(border: Border.all(color: Colors.yellow, width: 1)),
            ),
          );
        }),
      ),
    );
  }
}

two cases below
when the row > 100 and row < 100 enter image description here enter image description here

optional you can add mainAxisAlignment property to Row e.g.
mainAxisAlignment: MainAxisAlignment.spaceBetween,

like image 90
Nagual Avatar answered Sep 22 '25 02:09

Nagual


Try this

ConstrainedBox(
    constraints: const BoxConstraints(maxWidth: 10,maxHeigth:10),
    child: ChildWidget(...),
)
like image 37
ibrahimxcool Avatar answered Sep 22 '25 01:09

ibrahimxcool