android - 从另一个小部件 Flutter 更改文本字段的 textSize
问题描述
我需要通过单击另一个小部件中的图标来更改 textField 的 fontSize。所以我在这里有我的自定义文本字段小部件。
class StateTextField extends StatefulWidget {
final FocusNode focusNode = FocusNode();
final Function(bool,Widget) callback;
final String fontFamily = FontFamily.Arial.toString().split('.')[1];
double fontSize = 18;
final Function(bool) selected;
final bool highlighted = false;
bool hasFocus() {
return focusNode.hasFocus;
}
increaseFontSize() {
fontSize += 2;
}
decreasefontSize() {
if (fontSize > 0) fontSize -= 2;
}
StateTextField({@required this.callback,@required this.selected});
@override
_StateTextFieldState createState() => _StateTextFieldState();
}
在第二个小部件中,我使用了函数 increaseFontSize 和 reductionFontSize 来改变大小
onTap: () {
setState(() {
print(widget.textField.fontSize);
widget.textField.increaseFontSize();
print(widget.textField.fontSize);
});
}
单击按钮时大小会增加,但不会反映。我意识到这是因为 setState 不会改变 textField 的状态。那我应该遵循什么方法?
解决方案
有这种方法可以以某种方式帮助您。
STEP 1:不要在 StatefulWidget 中使用增减方法
第 2 步:将值存储在变量中并在同一个小部件本身中进行更改
class StateTextField extends StatefulWidget {
final FocusNode focusNode = FocusNode();
final Function(bool,Widget) callback;
final String fontFamily = FontFamily.Arial.toString().split('.')[1];
double fontSize = 18;
final Function(bool) selected;
final bool highlighted = false;
bool hasFocus() {
return focusNode.hasFocus;
}
StateTextField({@required this.callback,@required this.selected});
@override
_StateTextFieldState createState() => _StateTextFieldState();
}
StateTextFieldState extends State<StateTextField>{
double _fontSize;
@override
void initState(){
super.initState();
// setting the value from the widget in initialization of the widget to the local variable which will be used to do the increase-decrease operation
_fontSize = widget.fontSize;
}
void increaseFontSize() {
setState(() => _fontSize += 2);
}
void decreasefontSize() {
if (_fontSize > 0){
setState(() => _fontSize -= 2);
}
}
//in your widget method, you can perform your operation now in `onTap`
onTap: () {
print(_fontSize);
//call your increase method here to increase
_increaseFontSize()
}
}
让我知道这是否对您有所帮助。谢谢 :)
推荐阅读
- sql - 计算不同的分区
- css - 为变量设置平滑的 CSS 动画
- python - Python - 比较数据框中的值,如果它们相同,则将行附加到新的数据框中
- android - 我想为每个标记添加唯一的 clickListener
- sql - 错误:XML 声明必须是文档中的第一个节点,并且它之前不允许出现空白字符
- r - 根据 R 中的相似性将值添加到不同行的列
- excel - 带有 count 的 UDF 总是返回 0,或者一个错误
- mysql - sqlMessage:“列计数与第 1 行的值计数不匹配”节点 MySQL
- java - 如何控制我的 LWJGL 窗口 int LWJGL3 的帧速率?
- sql-server - SQL 视图转置数据