-2

I want the height of container

 Container( // how to get height of the container
    child: Text('hello,\nhow to get\nheight of the parent layout'),
 ),

I try this,

  return LayoutBuilder(
    builder:
        (BuildContext context, BoxConstraints constraints) {
      print(constraints.maxHeight);
      return Container( // how to get height of the container
        child: Text('hello,\nhow to get\nheight of the parent layout'),
      );
    },
  );

The height print always 0 value

HasanToufiqAhamed
  • 751
  • 1
  • 5
  • 17

2 Answers2

1

it will be worked for dynamic height, You need to bind your child with a parent widget

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: LayoutBuilder(
            builder:
                (BuildContext context, BoxConstraints constraints) {
              print(constraints.maxHeight);
              return Container(
                height: constraints.maxHeight, //set height of the container
                color: Colors.yellow,
                child: Text('hello,\nhow to get\nheight of the parent layout'),
              );
            },
          ),
        ),
      ),
    );
  }
}
Jahidul Islam
  • 11,435
  • 3
  • 17
  • 38
0

About Your code snippet

return LayoutBuilder(
    builder:
        (BuildContext context, BoxConstraints constraints) {
      print(constraints.maxHeight);
      return Container( // how to get height of the container
        child: Text('hello,\nhow to get\nheight of the parent layout'),
      );
    },
  );

You are trying to get child size. To get parent size, you need to use LayoutBuidler as child on that widget.

like this,

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: LayoutBuilder(
      builder: (context, bodyConstraints) {
        print("body height : ${bodyConstraints.maxHeight}");

        return Container(
          height: 200,
          color: Colors.deepOrangeAccent,
          child: LayoutBuilder(
            builder: (context, containerConstraints) {
              print("Container height ${containerConstraints.maxHeight}");

              return Text(
                " body Height: ${bodyConstraints.maxHeight} \n container height: ${containerConstraints.maxHeight}",
              );
            },
          ),
        );
      },
    ));
  }
}

does it solve your issue?

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56