I am trying to pass user id through app widgets using Stream provider but for some reason I am not able to access it through descendant widgets.. only the child.
class Auth {
final FirebaseAuth _auth = FirebaseAuth.instance;
Stream<User?> get user => _auth.userChanges();
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamProvider.value(
value: Auth().user,
initialData: null,
child:
MaterialApp(
home: InitialPage(),
),
);
}
}
class InitialPage extends StatelessWidget {
const InitialPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
if (user == null) {
return LoginPage();
} else {
return HomePage();
}
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
ElevatedButton(onPressed: () {
final user = Provider.of<User>
(context);print(user.uid);},
child: Text('add'))));}
When I press the button in the home screen I am getting this exception Tried to listen to a value exposed with provider, from outside of the widget tree.
You can't listen to changes in a button callback.
Try to wrap ElevatedButton
in a Builder
and call Provider.of<User>(context, listen: false)