在Flutter中使用setState时?
问题内容:
作为扑朔迷离的新手,setState
在Flutter
应用程序中使用时对我来说非常困惑。在下面的代码中searching
,在boolean
和var中resBody
使用了setState
。我的问题是,为什么只有searching
和resBody
里面的setState?为什么其他人没有名气?
var resBody;
bool searching = false,api_no_limit = false;
String user = null;
Future _getUser(String text) async{
setState(() {
searching = true;
});
user = text;
_textController.clear();
String url = "https://api.github.com/users/"+text;
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept":
"application/json"});
setState(() {
resBody = json.decode(res.body);
});
}
问题答案:
根据文档:
调用setState会通知框架此对象的内部状态已更改,该方式可能会影响此子树中的用户界面,这将导致框架为该State对象安排构建。
因此,如果小部件的状态更改 ,则 必须调用setState
以触发视图重建,并立即查看新状态所隐含的更改。
无论如何,以下片段都是等效的。
第一种情况(直接形式flutter create <myproject>
):
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
第二种情况:
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
_counter++;
setState(() {});
}
我不知道的原因是,如果第一种情况是常规的使用方式setState
,我会说是因为代码的可读性。