Stacked architecture - User persistance

406 Views Asked by At

I'm using the stacked architecture on my Flutter app. Everything is working fine but I have a problem now that I'm trying to implement the user authentication.

My user class should be available on all the widgets and screens that inherit my login widget. But I don't know how to do this, and I don't find this information on the research I made.

Should I use Provider on top of my Stacked architecture to pass my User class to the sub widgets?

For example, I have this view, linked to a ViewModel and I would like to have access to my User class in the view, but I don't know how to share it with this view since my User class is not available on this screen.


class SettingsViewModel extends BaseViewModel {
// Some methods and getters that I use in my View
}


class Settings extends StatefulWidget {
  @override
  _SettingsState createState() => _SettingsState();
}

class _SettingsState extends State<Settings> {
  @override
  Widget build(BuildContext context) {

    return ViewModelBuilder<SettingsViewModel>.reactive(
        viewModelBuilder: () => SettingsViewModel(),
        builder: (context, model, child) => Scaffold(
              body: SafeArea(
                  child: SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          // I would like to display here the name of my User
                          Text("Jhon"),
                          Icon(Icons.close),
                        ],
                      ),
                    // ... Rest of the view ...

1

There are 1 best solutions below

0
On

You don't need Provider on top of Stacked, because Stacked already uses Provider, it is a wrapper around it. I suggest you watch the creator's tutorial about Stacked architecture on Youtube.

I would save User object in a service (for example AuthService) and then import that service in my ViewModels where I need it.

(Stacked tutorial 1, Stacked tutorial 2, and what you probably need in this case tutorial about services)