TheMortiestMorty
TheMortiestMorty

Reputation: 705

Flutter: notifyListeners not working for any page other than the home page

My main.dart calls wrapper.dart (below). Depending on the global variable loggedIn, it shows either the Forms page or the Login page.

On the Forms page, the user can choose another page to go to. If I go to the Issue Parts page and change loggedIn to false, the app doesn't go back to the Login page. However, if I change loggedIn to false on the Forms page, the app correctly goes back to the Login page. Why does it only work on the Forms screen and not another screen?

Note - I don't want to overload this question with too much code so I've added only the bare minimum. If you think something is missing, please ask about it and I can either answer it or add it to the question.

wrapper.dart:

class Wrapper extends StatefulWidget {
  const Wrapper({super.key});
  @override
  State<Wrapper> createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {

  @override
  void initState() {
    super.initState(); ///Run this first
    initialize();
  }

  @override
  dispose() {
    super.dispose(); ///Run this last
  }

  void initialize() async {
    final globalsOneTimeRead = context.read<GlobalsProvider>();

    await globalsOneTimeRead.localDBInit();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<GlobalsProvider>(builder: (context, value, child) {
      if (value.loggedIn == true) {
        return const Forms();
      } else {
        return const Login();
      }
    });
  }
}

Forms Page:

//...

return GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => const IssueParts()),
                      );
                    },
                    child: Card(
                      child: ListTile(
                        title: Text(formsList[index]['Form'], style: const TextStyle(fontSize: 21),),
                      ),
                    ),
                  );

//...

Issue Parts Page:

//...

ElevatedButton(
  onPressed: () async {

    await globals.logout(); //sets loggedIn = false and calls notifyListeners();

  },
  child: const Text('LOGOUT'),
),

//...

Upvotes: 1

Views: 72

Answers (1)

聂超群
聂超群

Reputation: 2120

Two possible reason:

  1. IssueParts is not decentent node of GlobalsProvider.
  2. You forgot to call Navigator.pop(context); after await globals.logout();.

Upvotes: 2

Related Questions