我有一个 FloatingActionButton
需要在用户点击它时为 disabled
并等待结果从 onPressed
返回
Widget _fab() {
return FloatingActionButton(
child: Icon(Icons.done),
onPressed: _onFabTap,
);
}
void _onFabTap() async {
//Somehow disable the button here until the end of this method call
await _viewModel.doneEditing();
//now enable the button
}
附言我使用 ChangeNotifier
和 Provider
进行状态管理。
答案 0 :(得分:1)
只要将 fab 按钮保留为单独的小部件,就可以使用 setState 执行此操作,但如果您的 fab 按钮是更大的 Widget 的一部分,则应考虑将其移至单独的小部件或考虑使用 ValueNotifier
构建器
bool buttonEnabled = true;
void _onFabTap() async {
setState((){
bool buttonEnabled = false;
});
//Somehow disable the button here until the end of this method call
await _viewModel.doneEditing();
setState((){
bool buttonEnabled = true;
});
}
在构建方法中
Widget _fab() {
return FloatingActionButton(
child: Icon(Icons.done),
onPressed: buttonEnabled? _onFabTap:null,
);
}
答案 1 :(得分:1)
一种有效的方法是使用 ValueNotifier
,因为 setState
可能会影响应用性能。试试这个
ValueNotifier _isLoadingNotifier = ValueNotifier(false);
Widget _fab() {
return ValueListenableBuilder(
valueListenable: _isLoadingNotifier,
builder: (context, _isLoading, _) {
return FloatingActionButton(
child: Icon(Icons.done),
onPressed: !_isLoading ? _onFabTap : null,
);
},
);
}
void _onFabTap() async {
_isLoadingNotifier.value = true;
await _viewModel.doneEditing();
_isLoadingNotifier.value = false;
}
答案 2 :(得分:0)
你可以这样做:
Widget _fab() {
return FloatingActionButton(
child: Icon(Icons.done),
onPressed:_viewModel.isLoading? null: _onFabTap,
);
}
然后在您的 ChangeNotifier
中执行以下操作:
bool isLoading = false;
... doneEditing(...){
isLoading = true;
notifiyListeners();
...
// api call
...
isLoading = false;
notifiyListeners();
}