如何从 Flutter 中的流提供者获取价值

How to get value from stream provider in Flutter

我正在尝试使用 Stream 提供程序通过应用程序小部件传递用户 ID,但由于某种原因我无法通过后代小部件访问它。只有 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'))));}

当我按下主屏幕中的按钮时出现此异常 Tried to listen to a value exposed with provider, from outside of the widget tree.

您不能在按钮回调中监听变化。

尝试将 ElevatedButton 包装在 Builder 中并调用 Provider.of<User>(context, listen: false)