【发布时间】:2021-07-29 10:10:02
【问题描述】:
如何在不使用setState((){}) 的情况下获取TextFormField 的更新值?
在TextFormField 的onChanged 方法中,我将类变量设置为该值,但通常我们需要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 = val而setState({})用于重建小部件!更多@api.flutter.dev/flutter/widgets/State/setState.html -
这能回答你的问题吗? When do I use setState in Flutter?
-
@OMiShah 感谢您的链接!抱歉,我很困惑,即使要更新类变量,您也需要使用
setState((){}),现在一切都清楚了!仅当我想重建小部件时才必须使用 setState (比实际值更多的视觉) 例如,如果我在 Text() 小部件中显示用户键入的文本,那么我应该使用 setstate 所以 Text () 小部件将立即重建以显示更新的文本 -
是的......你明白了:)
标签: flutter