Created
March 8, 2019 13:55
-
-
Save liusilong/6ccb60098d46b9b9d9a9bbe14212e4c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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