我已经尝试过问题底部列出的来源中的代码。因此,到目前为止,我能够获取设备的物理和逻辑高度、屏幕键盘的逻辑高度,但我陷入了困境 - 获取小部件的逻辑高度。我尝试实施GlobalKey
但没有成功。我无法获得高度,并且发生了一个我没有成功解决的错误。以下代码中的多行注释中包含了错误的位置。该错误表示:“无法无条件访问属性‘size’,因为接收器可能为空。...”。我尝试使用?
和!
运算符来解决空条件,但没有任何效果。
如何解决这个问题以获得小部件的高度?
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey? _key01 = GlobalKey();
late final TextEditingController firstController;
String result = "";
String effective_available_screen_height = "";
String dimensions = "";
FlutterView view = WidgetsBinding.instance.platformDispatcher.views.first;
late Size size;
double width = 0;
double height = 0;
double height01 = 0;
@override
void initState() {
super.initState();
firstController = TextEditingController();
}
@override
void dispose() {
firstController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
Size ph_size = view.physicalSize;
double ph_height = ph_size.height;
size = MediaQuery.of(context).size;
width = size.width;
height = size.height;
final padding = MediaQuery.of(context).viewPadding;
height01 = height - padding.top - padding.bottom;
effective_available_screen_height = "$height01";
// Height of Keyboard when onscreen (ohterwise zero):
double keyboard_height = MediaQuery.of(context).viewInsets.bottom;
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Container(
padding: const EdgeInsets.all(5.0),
child: Column(
children: [
Container(
child: Row(
children: [
Expanded(
flex: 5,
child: Container(
padding: const EdgeInsets.all(5.0),
child: TextField(
key: _key01,
style: const TextStyle(
fontSize: 16,
),
controller: firstController,
keyboardType: TextInputType.number,
onChanged: (value) {
setState(() {
result = value;
/*
// The following gave error:
dimensions =
"${_key01?.currentContext.size.height}";
*/
dimensions = "${_key01?.currentContext}";
});
},
),
),
),
const Expanded(
flex: 5,
child: Text("Input Value"),
),
],
),
),
Text("Result = $result"),
Text("Total physical height = $ph_height"),
Text("Total logical height = $height"),
Text("Onscreen Keyboard height = $keyboard_height"),
Text(
"Working Height Available (logical) = $effective_available_screen_height"),
Text("Dimensions: $dimensions"),
],
),
),
);
}
}
帮助来源:
如果你想在执行任何操作时获取高度,你只需要使用它:
但是如果你想在渲染小部件时获取高度,你可以在 initState 上使用它: