Skip to content

Instantly share code, notes, and snippets.

@liusilong
Created March 8, 2019 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liusilong/6ccb60098d46b9b9d9a9bbe14212e4c2 to your computer and use it in GitHub Desktop.
Save liusilong/6ccb60098d46b9b9d9a9bbe14212e4c2 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
class GetWidgetWidthAndHeiget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
final GlobalKey globalKey = GlobalKey();
void _getWH() {
final containerWidth = globalKey.currentContext.size.width;
final containerHeight = globalKey.currentContext.size.height;
print('Container widht is $containerWidth, height is $containerHeight');
}
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final width = size.width;
final height = size.height;
print('width is $width; height is $height');
return Scaffold(
appBar: AppBar(
title: Text('Width & Height'),
),
body: Center(
child: Container(
key: globalKey,
color: Colors.redAccent,
width: width / 2,
height: height / 2,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _getWH,
child: Icon(Icons.adjust),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment