作为 Flutter 的新手,在 Flutter
应用程序中使用 setState
让我非常困惑。在下面的代码中,在 setState
中使用了 bool searching
和 var resBody
。我的问题是为什么只有 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);
});
}
最佳答案
根据docs :
Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.
因此,如果小部件的状态发生变化您必须调用 setState
触发 View 的重建并立即查看新状态所暗示的更改。
无论如何,下面的代码 fragment 是等价的。
第一种情况(直接形式 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
的常规方式,我会说是因为代码的可读性。
https://stackoverflow.com/questions/51283077/
相关文章:
android - 将自定义 boxshadow 添加到 Flutter 卡
flutter - 将容器缩小到较小的 child 而不是扩大到填充 parent
dart - flutter : Get Local position of Gesture Det
dart - 如何在 Flutter 中获取 Text 小部件的大小
unit-testing - Flutter/Dart 在单元测试中等待几秒钟
firebase - 如何使用 buildArguments 或其他任何东西在 Flutter/Fi
dart - Flutter 中的 Scaffold 和 MaterialApp 有什么区别?