usersina
usersina

Reputation: 1783

The best way to keep track of my global dart variable (that I can re-assign and read)

TL;DR: Do I need redux or bloc providers to use global variables/states ? Or is the simple code below enough ?

I'm making a flutter Education application that has a bunch of users in a database. The app has a simple login screen that changes to a "home.dart" view if the credentials are correct and also creates a "User" object which is then stored in a variable that I can pass as a parameter to "home.dart".

However if I want to pass that same User to other files, it quickly becomes a mess. So I want to find a way to keep track of the currently LoggedUser across all of my dart files.

I've tried ultimately created a "globals.dart" that is structured as so:

library education_app.globals;

import 'package:education_app/src/models/user.dart';

User loggedUser;
void setLoggedUser(User newUser) => loggedUser = newUser;

This solution seems to work just fine but I'm not convinced enough, since I've seen some examples use "state_bloc" & "state_provider".

So is this method actually viable? (or may cause some unexpected bugs)

Upvotes: 0

Views: 204

Answers (1)

Nour Shobier
Nour Shobier

Reputation: 555

Filip Hráček mention such approach in one of the Flutter conferences in 2018 and said that it will work fine but it's not a clean solution. It would be better if you use a provider at the root of your widget tree so that all widgets in the subtree can access it.

Here is an example about 2-factor authentication using provider and p.mvvm package: https://github.com/NourEldinShobier/pmvvm/tree/master/example

Upvotes: 2

Related Questions