Este pacote tem como objetivo fornecer uma funcionalidade ausente no firebase_auth, que é a capacidade de recarregar os dados do usuário do servidor e obter atualizações em tempo real com os novos dados.
Orientação gerada a partir de informações públicas. Apenas para referência.
O pacote firebase_user_stream expande o Firebase Auth permitindo a recarga em tempo real dos dados do usuário a partir do servidor e fornecendo um Stream com informações atualizadas sobre o usuário. Ele preenche uma lacuna no firebase_auth, que não possui suporte embutido para atualizar os dados do usuário e entregar atualizações em tempo real. Isso é particularmente útil para manter o estado do usuário preciso ao longo das sessões do aplicativo, especialmente quando os dados do usuário mudam no servidor. O pacote se integra perfeitamente aos fluxos de trabalho existentes do Firebase Auth e garante que os componentes da interface reflitam as últimas informações do usuário sem exigir lógica manual de atualização.
Casos de uso
Sincronização em tempo real de dados do usuário
Atualizando os dados do usuário após atualizações no lado do servidor
Manter o estado do usuário atualizado na interface
Manuseio de alterações no perfil do usuário em tempo real
Evitando dados de usuário obsoletos nos fluxos de autenticação
Principais recursos
Atualizações de usuário baseadas em fluxo
Recarregamento de dados do usuário do lado do servidor
Integração contínua com firebase_auth
Sincronização automática após alterações no estado de autenticação
Funcionalidade leve e focada
Indicado para
Aplicativos que exigem dados de usuário em tempo real
Usuários do Firebase Auth que precisam de atualizações em tempo real
Desenvolvedores evitando lógica manual de atualização do usuário
Projetos com perfis de usuário dinâmicos
Aplicativos multiplataforma usando o Firebase
Considerações
Requer firebase_auth para ser configurado
Limitado apenas à atualização de dados do usuário
Nenhuma funcionalidade de autenticação adicional
Depende da estabilidade do backend do Firebase
Não necessário se os dados do usuário não mudarem após o login
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
Firebase User Stream
A Package for subscribing to User reload updates.
ATTENTION
Since firebase_auth version 0.18.0 this library is mostly pointless as firebase_auth (finally) adds
authStateChanges() which mostly substitutes this package, fixing the problem described below.
I mean mostly because here we can have further functionality like:
Reloading based on a predicate
Reload and get the user in the same line.
Although that's not useful to most people.
The (old, pre firebase_auth version 0.18.0) problem
The FirebaseAuth Flutter plugin provides a Stream<FirebaseUser> with
onAuthStateChanged, which is useful for getting updates when a user signs-in
or signs-out, but it fails to provide an update when the user data itself changes.
A common problem is when we want to detect if the user has just verified his e-mail
address, in other words get if FirebaseUser.isEmailVerified changed its value, as
this is updated server-side and not pushed to the app.
FirebaseAuth.currentUser() will only detect changes made locally to the user, but
if any server-side changes occur, it won't detect them, unless FirebaseUser.reload()
is called first, then we need to call FirebaseAuth.currentUser() again to get
the reloaded user, but still this user won't be emitted by onAuthStateChanged.
The solution
There are two ways we can get a new FirebaseUser, with the latest information on
the server:
Do it manually:
Future<FirebaseUser> reloadCurrentUser() async {
FirebaseUser oldUser = awaitFirebaseAuth.instance.currentUser();
oldUser.reload();
FirebaseUser newUser = awaitFirebaseAuth.instance.currentUser();
// Add newUser to a Stream, maybe merge this Stream with onAuthStateChanged?return newUser;
}
Let us do it for you!
Getting Started
After you install this package you can use FirebaseUserReloader to get reload updates
using the onUserReloaded and onAuthStateChangedOrReloaded streams.
FirebaseUserReloader internally uses the
FirebaseAuth instance returned by FirebaseAuth.instance, so your entire App will have the same
Singleton instance, you don't have to configure anything, it just works out of the box.
In order to get reload updates just do:
var subscription = FirebaseUserReloader.onUserReloaded.listen((user) {
// A new user will be printed each time there's a reloadprint(user);
});
// This will trigger a reload and the reloaded user will be emitted by onUserReloadedFirebaseUserReloader.reloadCurrentUser();
subscription.cancel();
Each time you call reloadCurrentUser() a reloaded user will be emitted by
onUserReloaded.
Keep in mind that onUserReloaded will emit reloaded users, they might be new, or just the
current one if the user data didn't change.
As a bonus, you can provide a predicate to reloadCurrentUser(), in order to only get reloaded
users that matter to you:
var subscription = FirebaseUserReloader.onUserReloaded.listen((user) {
// A new user will be printed each time there's a reloadprint(user);
});
// This will trigger a reload and the reloaded user will be emitted by onUserReloaded// only if isEmailVerified == trueFirebaseUserReloader.reloadCurrentUser((user) => user.isEmailVerified);
subscription.cancel();
You also can get the reloaded user as the return value of reloadCurrentUser, but in this case,
the predicate will be ignored, and the reloaded user will always be returned.
var user = awaitFirebaseUserReloader.reloadCurrentUser();
If you want to listen for updates on sign-ins, sign-outs and user reloads, use
onAuthStateChangedOrReloaded instead, it's just a convenient merge of onUserReloaded and
FirebaseAuth.onAuthStateChanged and it works as a broadcast Behavior Subject:
var subscription = FirebaseUserReloader.onAuthStateChangedOrReloaded.listen((user) {
// A new user will be printed each time there's a reload, login or logoutprint(user);
});
// This will trigger a reload and the reloaded user will be emitted by onUserReloaded// only if isEmailVerified == trueFirebaseUserReloader.reloadCurrentUser((user) => user.isEmailVerified);
subscription.cancel();
Both onAuthStateChangedOrReloaded and onUserReloaded are broadcast streams.
Testing
This library uses static methods for easiness of usage, but this doesn't limit its
testability.
FirebaseUserReloader can be injected with a mocked instance of FirebaseAuth for unit testing.
For any examples on how to control its behavior under tests, please take a look at our
own tests inside the test folder.