flutter 扑动|禁用按钮按下直到当前呼叫结束

6jjcrrmo  于 2022-12-19  发布在  Flutter
关注(0)|答案(4)|浏览(104)

我有一个FloatingActionButton,当用户点击它并等待从onPressed返回结果时,它需要是disabled

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
}

P.S.我正在使用ChangeNotifierProvider进行状态管理。

mxg2im7a

mxg2im7a1#

一种有效的方法是使用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;
}
7gcisfzg

7gcisfzg2#

只要将fab按钮作为一个单独的小部件,就可以使用setState执行此操作,但如果fab按钮是更大的小部件的一部分,则应考虑将其移动到一个单独的小部件或考虑使用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,
  );
}
toiithl6

toiithl63#

您可以执行以下操作:

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();
}
anauzrmj

anauzrmj4#

bool isLoading = false;
ontap() async {
if(!isLoading){
isLoading = true;
var rsponse = await asyncTask();
isLoading = false;
 }
}

相关问题