[英]Will my whole widget tree rebuild when a keyboard appears?
I am trying to build a responsive mobile app so I found an approach were i would divide the sreen into definite number of grids and get the grid width and height and then use this width and height to size my widgets我正在尝试构建一个响应式移动应用程序,所以我找到了一种方法,我将屏幕划分为一定数量的网格并获取网格宽度和高度,然后使用此宽度和高度来调整我的小部件的大小
Question :问题:
I would definitly get my screen's size from MediaQuery.of(context) but since i will only use it once to do my calculations will my widget tree rebuild (assuming i did this calculation in my root widget) whenever a keyboard appears or not?我肯定会从 MediaQuery.of(context) 获取我的屏幕大小,但是由于我只会使用它一次来进行计算,无论何时出现键盘,我的小部件树都会重建(假设我在我的根小部件中进行了此计算)? And if it will rebuild should i do the calculations in a different place?如果它会重建,我应该在不同的地方进行计算吗?
No, if you didn't place any set state or callback during that rebuild the widget when you open the keyboard.不,如果您在打开键盘时没有在重建小部件期间放置任何设置状态或回调。 However, the issue can be easily resolved by putting your main widget "below" the Scaffold in a SingleChildScrollView to avoid rendering issues.但是,通过将您的主要小部件“低于” Scaffold 中的SingleChildScrollView以避免呈现问题,可以轻松解决该问题。
If you absolutely need to perform actions when the keyboard appears you can use a FocusNode in the textField and add a listener to it with the addListener method.如果您绝对需要在键盘出现时执行操作,您可以在 textField 中使用FocusNode并使用addListener方法为其添加侦听器。 By passing a function to add Listener, you can trigger a setState every time you need, causing the widget to rebuild with the new parameters.通过传递一个函数来添加侦听器,您可以在每次需要时触发一个 setState,从而使用新参数重新构建小部件。
This is a very simplified version of what I mean:这是我的意思的一个非常简化的版本:
class MyWidget extends StatefulWidget{
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
FocusNode _focusNode;
int state=0;
@override
Widget build(BuildContext context) {
return Container(
height: state==0?100:200, //change the height depending on "state"
child: TextField(
focusNode: _focusNode,
),
);
}
void onFocus(){
setState(() {
//Check if the focus node is focused
if(_focusNode.hasFocus) state=1; //Change the value of the state
});
}
@override
void initState() {
super.initState();
_focusNode=FocusNode();
_focusNode.addListener(onFocus); //Here on focus will be called
}
@override
void dispose() {
super.dispose();
_focusNode.dispose();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.