首页 > 解决方案 > 从另一个小部件 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 的状态。那我应该遵循什么方法?

标签: androidflutterflutter-layout

解决方案


有这种方法可以以某种方式帮助您。

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()
  }
}

让我知道这是否对您有所帮助。谢谢 :)


推荐阅读