【问题标题】:How is the class variable being updated without calling setstate?如何在不调用 setstate 的情况下更新类变量?
【发布时间】:2021-07-29 10:10:02
【问题描述】:

如何在不使用setState((){}) 的情况下获取TextFormField 的更新值?

TextFormFieldonChanged 方法中,我将类变量设置为该值,但通常我们需要setState((){}) 来更新该值。我只是想知道这是如何工作的?

class ResetPasswordPage extends StatefulWidget {
  const ResetPasswordPage({ Key? key }) : super(key: key);

  @override
  _ResetPasswordPageState createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends State<ResetPasswordPage> {

String _currentPassword = '';

  void onChanged(){
    print('current Password is: ');
    print(_currentPassword); ----------->this is printing the updated value, without setstate?

  }


  @override
  Widget build(BuildContext context) {
    return Container(
       TextFormField(
         onChanged: (val) => {
           _currentPassword = val,
           onChanged()
         },
      ),
    )
 }



}

【问题讨论】:

  • 您已经在使用_currentPassword = valsetState({}) 用于重建小部件!更多@api.flutter.dev/flutter/widgets/State/setState.html
  • 这能回答你的问题吗? When do I use setState in Flutter?
  • @OMiShah 感谢您的链接!抱歉,我很困惑,即使要更新类变量,您也需要使用setState((){}),现在一切都清楚了!仅当我想重建小部件时才必须使用 setState (比实际值更多的视觉) 例如,如果我在 Text() 小部件中显示用户键入的文本,那么我应该使用 setstate 所以 Text () 小部件将立即重建以显示更新的文本
  • 是的......你明白了:)

标签: flutter


【解决方案1】:

变量值确实会改变而不需要使用 setState,setState 只需要告诉 Flutter UI 必须改变以反映数据的变化。

来自Flutter docs

调用 setState 会通知框架此对象的内部状态已发生更改,可能会影响此子树中的用户界面,这会导致框架为此 State 对象安排构建。

【讨论】:

    【解决方案2】:

    你可以创建Notifier -> listener,然后设置listener来监听Notifier,所以Notifier(controller)上的任何更新都会通知listener(TextFormField)自己更新。

    像这样:

    final _controller = TextEditingController();
    
    child: TextFormField(
        controller: _controller,
        decoration: //decoration,
    ),
    

    当您调用此 _controller.text 时,它将通知此 TextEditingController 需要更新的所有侦听器,然后您将获得与 setState((){}) 相同的结果。

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多