为什么消费者构建函数在notifylisteners之后可能没有被调用?

问题描述 投票:0回答:1

考虑

class AquariusProApp extends StatelessWidget {
  final LocalStorage cLocalStorage;
  final Database cDatabase;

  const AquariusProApp(
      {super.key, required this.cDatabase, required this.cLocalStorage});

  @override
  Widget build(BuildContext context) {
    myDebugPrint("in AquariusProApp build");
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<Authenticator>(
            create: (context) => Authenticator(
                cDatabase: cDatabase, cLocalStorage: cLocalStorage)),
      ],
      child: MaterialApp(
        title: kProgramName,
        theme: aquariumManagerTheme,
        home: Consumer<Authenticator>(builder: (context, authenticator, child) {
          myDebugPrint("in consumer");
          if (authenticator.isLoading) {
            return const Center(child: CircularProgressIndicator());
          } else if (authenticator.hasToken) {
            return HomeView(cAuthenticator: authenticator);
          } else {
            return AuthenticatorView(cAuthenticator: authenticator);
          }
        }),
      ),
    );
  }
}

我更改 ChangeNotifier Authenticator 类中的变量并调用notifylisteners:

void resetAuthentication() {
    // we clear the saved token and reset the screen to the login page
    cLocalStorage.deleteSecureStorage(kAuthenticationInfo);
    _isPasswordBad = false;
    _isLoading = false; // we are NOT loading; we are headed to the authenticator screen
    _hasToken = false;
    myDebugPrint("in resetAuthentication");
    myDebugPrint("about to call notify 3");
    notifyListeners();
  }

但是,消费者构建代码永远不会从此特定函数调用。为什么会这样?

有很多类似场景的参考,但没有一个能解决我的特定问题。

flutter provider
1个回答
0
投票

上面代码中未显示的问题是我替换了当前路线

Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                      builder: (context) => HomeView(cAuthenticator: widget.cAuthenticator), // homeview will have a logout button, so it will need the authenticator
                    ),
                  );

所以它不复存在了。

感谢https://github.com/moffatman的回答。

© www.soinside.com 2019 - 2024. All rights reserved.