0

I would like to get some help. I don't understand why something is not rebuilding properly. I have an app.dart which provides all stores and the body of the Scafold is a home page,

class HomePage extends StatelessWidget {
  const HomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthStore>(
      builder: (__, AuthStore authStore, _) {
        debugPrint('--- $authStore');
        return SafeArea(
          child: authStore.authenticated
              ? const AuthenticatedScreen()
              : const LoginScreen(),
        );
      },
    );
  }
}

the login screen does its job, and updates the store correctly, I don't understand why the home screen is not updated when authenticated changes to true I tried adding an observer with the same result e.g. no rebuild

class HomePageStateless extends StatelessWidget {
  const HomePageStateless({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthStore>(builder: (__, AuthStore authStore, _) {
      debugPrint('--- $authStore');
      return Observer(
        builder: (_) => SafeArea(
          child: authStore.authenticated
              ? const AuthenticatedScreen()
              : const LoginScreen(),
        ),
      );
    });
  }
}

what I'm missing here while this widget works as expected

class HomePage extends StatefulWidget {
  const HomePage({
    Key key,
  }) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  AuthStore _authStore;
  final List<ReactionDisposer> _disposers = <ReactionDisposer>[];
  bool _authenticated = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    for (ReactionDisposer disposer in _disposers) {
      disposer();
    }
    _disposers.clear();

    _authStore ??= Provider.of<AuthStore>(context);

    _disposers.add(
      autorun(
        (_) {
          print('home store $_authStore');
          if (_authenticated != _authStore.authenticated) {
            setState(() {
              _authenticated = _authStore.authenticated;
            });
          }
        },
      ),
    );
  }

  @override
  void dispose() {
    for (ReactionDisposer disposer in _disposers) {
      disposer();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: _authenticated ? const AuthenticatedScreen() : const LoginScreen(),
    );
  }
}

And I know this shouldn't be the correct way, but the autorun fire consistently when the store changes

ZlatiP
  • 185
  • 6

1 Answers1

0

Use what you u want to rebuild in a void method below the state and statefull widget instead of stateless one.