https://felangel.github.io/bloc/#/flutterlogintutorial

我的代码在GitHub中:
链接-https://github.com/mymomisacoder/bloc_login2

对于本教程,我想寻求有关如何在主页上(登录时)添加/显示用户名的建议。

预期输入:



所需事件:



我尝试了2种方法:

方法1:在userrepo类中创建一个getusername()

方法2:在userrepo类中分配一个值并通过blocprovider访问

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final AuthenticationBloc authenticationBloc =
    BlocProvider.of<AuthenticationBloc>(context);

    final LoginBloc loginBloc = BlocProvider.of<LoginBloc>(context);

//method2
    **//String username2 = loginBloc.usernamebloc;

//method1
    String username2 = loginBloc.userRepository.getUserName().toString();**
    print("$username2");

    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              RaisedButton(
              child: Text('logout'),
              onPressed: () {
                authenticationBloc.dispatch(LoggedOut());
                },
              ),

              Center(
                child: Text("Hello"),
                **//child: Text("$username2"),**
              ),
            ],
          ),
        ),
      ),
    );
  }
}

用户回购类别
class UserRepository {

  String username1;


  Future<String> authenticate({
    @required String username,
    @required String password,
  }) async {
    await Future.delayed(Duration(seconds: 1));
//method2
    username1 = username;
    return 'token';
  }

  Future<void> deleteToken() async {
    /// delete from keystore/keychain
    await Future.delayed(Duration(seconds: 1));
    return;
  }

  Future<void> persistToken(String token) async {
    /// write to keystore/keychain
    await Future.delayed(Duration(seconds: 1));
    return;
  }

  Future<bool> hasToken() async {
    /// read from keystore/keychain
    await Future.delayed(Duration(seconds: 1));
    return false;
  }

//method1
  **Future<String> getUserName() async {
    await Future.delayed(Duration(seconds: 1));
    return username1;
  }**
}

主页
class SimpleBlocDelegate extends BlocDelegate {
  @override
  void onEvent(Bloc bloc, Object event) {
    super.onEvent(bloc, event);
    print(event);
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print(transition);
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {
    super.onError(bloc, error, stacktrace);
    print(error);
  }
}

void main() {
  BlocSupervisor.delegate = SimpleBlocDelegate();
  final userRepository = UserRepository();
  runApp(
    BlocProvider<AuthenticationBloc>(
      builder: (context) {
        return AuthenticationBloc(userRepository: userRepository)
          ..dispatch(AppStarted());
      },
      child: App(userRepository: userRepository),
    ),
  );
}

class App extends StatelessWidget {
  final UserRepository userRepository;

  App({Key key, @required this.userRepository}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BlocBuilder<AuthenticationBloc, AuthenticationState>(
        bloc: BlocProvider.of<AuthenticationBloc>(context),
        builder: (BuildContext context, AuthenticationState state) {
          if (state is AuthenticationUninitialized) {
            return SplashPage();
          }
          if (state is AuthenticationAuthenticated) {
            return HomePage();
          }
          if (state is AuthenticationUnauthenticated) {
            return LoginPage(userRepository: userRepository);
          }
          if (state is AuthenticationLoading) {
            return LoadingIndicator();
          }
        },
      ),
    );
  }
}

错误代码:

小工具图书馆的异常(exception)情况
构建HomePage(dirty)时引发了以下断言:
使用不包含LoginBloc类型的Bloc的上下文调用BlocProvider.of()。
从传递给的上下文开始找不到祖先
BlocProvider.of()。
如果发生以下情况,可能会发生这种情况:
1.您使用的上下文来自BlocProvider上方的小部件。
2.您使用了MultiBlocProvider,但未明确提供BlocProvider类型。

好的:BlocProvider(builder:(context)=> LoginBloc())
错误:BlocProvider(builder:(context)=> LoginBloc())。
使用的上下文是:HomePage(dirty)

最佳答案

我可以通过执行以下操作解决问题。

将UserRepository中的getUserName()方法更改为返回String(而不是Future)。因此,代码如下所示:

String getUserName()  {
    return username1;
  }

更改了HomePage的定义,以接受UserRepository参数。现在,定义如下所示:
class HomePage extends StatelessWidget {
  final String userName;
  HomePage({Key key, @required this.userName})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
// ...

最后,将登录块行注释为恕我直言,到目前为止,您在编写的总体Homepage代码中没有任何用处。新代码:
@override
  Widget build(BuildContext context) {
    final AuthenticationBloc authenticationBloc =
    BlocProvider.of<AuthenticationBloc>(context);

    //final LoginBloc loginBloc = BlocProvider.of<LoginBloc>(context);

    //String username2 = loginBloc.usernamebloc;
    String username2 = userName;
    print("$username2");

这可行。您将在控制台窗口中看到用户名。

08-15 20:58