Release模式下首次调用Get.height与Get.width输出0.0的问题求助
解决GetX首次构建时Get.height/Get.width为0的问题
问题原因
首次执行build方法时,GetX的全局上下文Get.context还未完成绑定,导致Get.height/Get.width无法获取到正确的屏幕尺寸,返回默认值0.0;调用setState触发Widget重新构建后,Get.context已完成绑定,就能拿到实际尺寸。
解决方案
方案1:利用帧回调获取尺寸
在页面的initState中添加帧绘制完成后的回调,此时UI已完成首次渲染,Get.context处于就绪状态:
class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override void initState() { super.initState(); // 首次帧绘制完成后执行回调 WidgetsBinding.instance.addPostFrameCallback((_) { print(Get.height); // 输出实际高度 print(Get.width); // 输出实际宽度 // 若需更新UI,可在此调用setState或使用GetX状态管理 }); } @override Widget build(BuildContext context) { // 避免首次build输出0.0,可添加上下文判断 if(Get.context != null){ print(Get.height); print(Get.width); } return Scaffold( // 原代码保持不变 appBar: AppBar(title: Text(widget.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('You have pushed the button this many times:'), Text('$_counter', style: Theme.of(context).textTheme.headline4), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
方案2:重写didChangeDependencies方法
didChangeDependencies会在Widget依赖的上下文变化时调用,此时Get.context已完成绑定:
class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override void didChangeDependencies() { super.didChangeDependencies(); print(Get.height); // 输出实际高度 print(Get.width); // 输出实际宽度 } @override Widget build(BuildContext context) { // 原代码保持不变 return Scaffold( appBar: AppBar(title: Text(widget.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('You have pushed the button this many times:'), Text('$_counter', style: Theme.of(context).textTheme.headline4), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
方案3:直接使用MediaQuery替代
如果仅需获取尺寸,可直接通过当前上下文的MediaQuery获取,无需依赖GetX全局方法:
@override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; print(size.height); // 输出实际高度 print(size.width); // 输出实际宽度 return Scaffold( // 原代码保持不变 ); }
全局尺寸初始化优化
若需全局复用屏幕尺寸,可在GetMaterialApp的builder中提前初始化,确保后续任意位置都能直接使用:
class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return GetMaterialApp( enableLog: true, title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue), builder: (context, child) { // 初始化全局尺寸 final size = MediaQuery.of(context).size; // 可选:将尺寸存入GetX全局变量,方便后续调用 Get.put<Size>(size); return child!; }, home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } }
内容的提问来源于stack exchange,提问作者Senthur Kumaran
相关产品推荐
相关产品推荐

