以下是块(简化):

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
    );
  }
}

以下是我在登录屏幕中尝试访问它的方式:
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();
  }

错误:
在空值上调用了getter“loggedin”。
那么,为什么这个集团是空的呢?我该怎么解决这个问题?

最佳答案

在这一行中,布洛克普罗佛希望有一个布洛克。

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

你不能在这里通过你的集团。
按如下方式传递:
home: BlocProvider<LoginBloc>(child: LoginScreen(),bloc: LoginBloc()),

BlocProvider<LoginBloc>表示定义要通过的块的类型。

10-06 01:24