首页 > 解决方案 > 通过 ChangeNotifierProvider 加载状态未显示

问题描述

这是我的代码。我想CircularprogressIndicator在点击时显示SpeedDialChild。所以我做ChangeNotifier了如下。并CircularprogressIndicator使用Consumer. 但Consumer不会更新我的用户界面。如何解决这个问题?

Widget build(BuildContext context) {
    return ChangeNotifierProvider<loading>(
      create: (_) => loading(),
      child: Scaffold(
        body: Stack(
          children: [
            Container(
              child: GoogleMap(
                initialCameraPosition: _currentlo,
              ),
            ),
            Consumer<loading>(
              builder: (context, value, child) => value.getloading() ?
              Center(child: CircularProgressIndicator()) : Container(),
            ),
          ],
        ),
        floatingActionButton: Builder(
          builder: (BuildContext context){
            return SpeedDial(
              children: [
                SpeedDialChild(
                    backgroundColor: Colors.white,
                    child: Icon(Icons.refresh, color: Colors.black,),
                    onTap: (){
                      Provider.of<loading>(context, listen: false).yesloading();
                      refreshMarkers();
                      Provider.of<loading>(context, listen: false).noloading();
                    }
                ),
              ],
            );
          },
        ),
      ),
    );
  }

class loading with ChangeNotifier{
  bool _isloading = false;

  bool getloading(){
    return _isloading;
  }

  void yesloading(){
    _isloading = true;
    notifyListeners();
  }

  void noloading(){
    _isloading = false;
    notifyListeners();
  }
}

标签: flutterdart

解决方案


发生这种情况是因为您立即(同步)再次将加载变量设置为 false:

Provider.of<loading>(context, listen: false).noloading();

如果删除此行,将显示加载指示器。

你可能想打电话给await你。refreshMarkers如果refreshMarkers返回 a Future,您应该能够做到这一点:

onTap: () async {
  Provider.of<loading>(context, listen: false).yesloading();
  await refreshMarkers();
  Provider.of<loading>(context, listen: false).noloading();
}

现在,您将在refreshMarkers完成时看到加载指示器。


了解 Dart 中的异步编程
此外,您可以并且可能应该查看Effective Dart:样式指南,以使您的代码具有可读性。


推荐阅读