flutter 无法从方法“build”返回类型为“MultiProvider”的值,因为它的返回类型为“Widget”

ivqmmu1c  于 2023-01-27  发布在  Flutter
关注(0)|答案(1)|浏览(136)

我已经尝试使用StreamProvider.value将用户身份验证状态更改流式传输到MaterialApp。但我收到此错误:无法从方法“build”返回类型为“MultiProvider”的值,因为它的返回类型为“Widget”。这是pubspec.yaml firebase_core: ^0.5.0 firebase_auth: ^0.18.0+1 cloud_firestore: ^0.14.0+2 provider: ^4.3.2+2中的依赖项
我想不出来。我被困住了,请帮帮我。先谢谢你的帮助。

import 'package:provider/provider.dart';
    import 'package:flutter/material.dart';
class MyAwesomeApp extends StatelessWidget {

@override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [StreamProvider<Usr>.value(value: Authenticate().userStream)],
      builder: (context, child) {
        return MaterialApp(
          home: Wrapper(),
        );
      },
    ); 
  }
}

//这是保存流的Authenticate类

import 'package:firebase_auth/firebase_auth.dart';

class Authenticate {
  //create an instance of firebase auth
  FirebaseAuth _auth = FirebaseAuth.instance;

  // Create a new user instance from my user model
  Usr _userFromFirebaseUser(User user) {
    return user != null ? Usr(uid: user.uid) : null;
  }

  // set up auth stream to listen to user auth status
  Stream<Usr> get userStream {
    return _auth.authStateChanges().map(
        _userFromFirebaseUser); // shorter way of mapping to user custom user object
    // .map((User user) => _userFromFirebaseUser(user)); //longer one
  }

  // sign in anon
  Future signInAnon() async {
    try {
      UserCredential response = await _auth.signInAnonymously();
      User user = response.user;
      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}
kxeu7u2r

kxeu7u2r1#

试试这个

import 'package:flutter/material.dart';
import 'package:provider/provider.dart' as statemanagement;

import 'models/model_provider.dart';
import 'modules/screen_root.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return statemanagement.MultiProvider(
      providers: [
        statemanagement.Provider<ModelProvider>(
          create: ((_) => ModelProvider())),
        ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Multi Provider',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const ScreenRoot(),
      ),
    );
  }
}

相关问题