androidiosflutter

How can I pass data to multiple stateful pages in Flutter?


So, I'm trying to pass data from one page to multiple pages, but here's the catch: I only want to actually navigate to one of them. I'm using this code snippet to navigate to the next page:

     Navigator.push(
             context,
             MaterialPageRoute(
                 builder: (context) =>
                     TodayPage(lg_username: unameController.text)),).then((value) => _login(lg_username));

But now I need the lg_username data to be available in multiple other pages without actually navigating to them. Any thoughts on how I could achieve this?


Solution

  • Try this follow:

    create file static_variable.dart

    class StaticVariable {
      static UserModel? user;
      static String? userId;
    }
    

    save userId or user data to StaticVariable

    ElevatedButton(
            child: const Text('Navigator'),
            onPressed: () {
              StaticVariable.userId = 'YOUR USER ID';
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) =>
                        TodayPage(lg_username: unameController.text)),);
            },
          )
    

    Then, you can call StaticVariable in any file

    Text(StaticVariable.userId ?? '')