使用通用bloc提供程序时bloc不会初始化

时间:2019-04-30 08:16:40

标签: dart flutter

这是集团(简体):

import 'package:autobleidas_flutter/bloc/bloc_base.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:rxdart/rxdart.dart';

class LoginBloc extends BlocBase {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  final PublishSubject<bool> loggedIn = PublishSubject<bool>();
  final PublishSubject<bool> loading = PublishSubject<bool>();

}

这是集团供应商:

class BlocProvider<T> extends InheritedWidget {
  final T bloc;

  BlocProvider({Key key, Widget child, this.bloc})
      : super(key: key, child: child);

  static T of<T extends BlocBase>(BuildContext context) {
    final type = _typeOf<BlocProvider<T>>();
    return (context.inheritFromWidgetOfExactType(type) as BlocProvider).bloc;
  }

  static Type _typeOf<T>() => T;

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}

但是,在LoginScreen中,我无法访问集团的loggedIn主题。这是从main打开LoginScreen并将团块传递给它的方法:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      localizationsDelegates: GlobalMaterialLocalizations.delegates,
      supportedLocales: allTranslations.supportedLocales(),
      home: BlocProvider<LoginBloc>(child: LoginScreen()), // <-------- HERE
    );
  }
}

这是我尝试在LoginScreen中访问它的方法:

class _LoginScreenState extends State<LoginScreen> {
  bool _isLoading = false;

  @override
  void didChangeDependencies() {
    LoginBloc bloc = BlocProvider.of<LoginBloc>(context);

    bloc.loggedIn.listen((isLoggedIn) => Navigator.of(context).push(
        MaterialPageRoute(
            builder: (BuildContext context) => RegistrationScreen())));

    bloc.loading.listen((state) => setState(() => _isLoading = state));
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
     return Container();
  }

错误:

  

获取器“ loggedIn”在null上被调用。

那为什么bloc为null?我该如何解决?

1 个答案:

答案 0 :(得分:1)

在这一行中,BlocProvder需要一个集团。

home: BlocProvider<LoginBloc>(child: LoginScreen()),

您没有在这里通过集团。

按如下所示传递它:

home: BlocProvider<LoginBloc>(child: LoginScreen(),bloc: LoginBloc()),

BlocProvider<LoginBloc>意味着您定义了要通过的集团的类型。