Flutter setState()运行但不运行';t触发器生成()
下面的代码通过Flutter setState()运行但不运行';t触发器生成(),flutter,dart,setstate,Flutter,Dart,Setstate,下面的代码通过toggleLoadingScreen()显式调用setState() toggleLoadingScreen()被调用两次: 提交表单时,我会切换加载屏幕(),使其成为\u isload=true,并呈现加载屏幕(这不会发生,因为未触发build()) 提交表单后,为了完整起见,即使页面会弹出,我也会切换loadingscreen()使\u isLoading=false。(build()被触发) 问题:为什么第一次调用时没有触发toggleLoadingScreen()bu
toggleLoadingScreen()
显式调用setState()
toggleLoadingScreen()
被调用两次:
提交表单时,我会切换加载屏幕()
,使其成为\u isload=true
,并呈现加载屏幕(这不会发生,因为未触发build()
)
切换loadingscreen()
使\u isLoading=false
。(build()
被触发)
toggleLoadingScreen()
build()
编辑:在中放置切换加载屏幕()
,然后
方法似乎可以工作,但我不知道它工作的原因是什么
类ModifyProductsScreen扩展StatefulWidget{
@凌驾
_ModifyProductsScreenState createState()=>\u ModifyProductsScreenState();
}
类_ModifyProductsScreenState扩展状态{
//…一些代码
void toggleLoadingScreen(){
设置状态(){
_isLoading=!\u isLoading;
});
}
无效保存(构建上下文){
如果(_formKey.currentState!.validate()){
_formKey.currentState!.save();
toggleLoadingScreen();//运行但不触发生成()
//新产品
如果(_editedOrNewProduct==null){
//将对象分配给_editedOrNewProduct
//更新产品列表
Provider.of(上下文,侦听:false)
.addProduct(_editedOrNewProduct!)
.那么(
()=>Navigator.of(context.pop(),
);
toggleLoadingScreen();//运行和触发生成()
}
}
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:正文(
“添加产品”,
),
行动:[
图标按钮(
按下时:()=>保存(上下文),
图标:图标(
图标。保存,
),
),
],
),
正文:_正在加载
?中心(
子级:CircularProgressIndicator.adaptive(),
)
:FormBuilder(…某些代码),
}
也许\u editedOrNewProduct
为空,并且切换加载屏幕
触发两次?\u editedOrNewProduct
实际上应该为空,预期行为是切换加载屏幕
触发两次(一次为加载屏幕,另一次为非加载屏幕)。但是第一个切换加载屏幕
似乎不会触发构建
如果editedOrNewProduct为空,则切换加载屏幕会触发两次,并且您的UI不会更新,因为加载已返回到其原始状态。我假设您希望在加载产品后调用第二个切换加载屏幕,并且它应该是这样的在当前调用Navigator.of(context.pop()@pskink的then调用中,可能会调用re()@pskink,不幸的是,只执行了一次生成。@AlexSchneider,是的,它会触发两次,但生成只运行一次,这让我感到困惑。
class ModifyProductsScreen extends StatefulWidget {
@override
_ModifyProductsScreenState createState() => _ModifyProductsScreenState();
}
class _ModifyProductsScreenState extends State<ModifyProductsScreen> {
//...some code
void toggleLoadingScreen() {
setState(() {
_isLoading = !_isLoading;
});
}
void save(BuildContext context) {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
toggleLoadingScreen(); //Runs but doesn't trigger build()
//New product
if (_editedOrNewProduct == null) {
//Assign object to _editedOrNewProduct
//Update product list
Provider.of<Products>(context, listen: false)
.addProduct(_editedOrNewProduct!)
.then(
(_) => Navigator.of(context).pop(),
);
toggleLoadingScreen();//Runs & trigger build()
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Add Products",
),
actions: [
IconButton(
onPressed: () => save(context),
icon: Icon(
Icons.save,
),
),
],
),
body: _isLoading
? Center(
child: CircularProgressIndicator.adaptive(),
)
: FormBuilder(... some code),
}