Flutter Bloc 教程 - 如何显示用户名,即来自其他页面的值

Flutter Bloc Tutorial - How to show user name i.e. value from other page

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

我的代码在GitHub: Link - https://github.com/mymomisacoder/bloc_login2

对于本教程,我想就如何 add/show 主页中的用户名(登录时)寻求建议。

预期输入:

In login page, Login button is pressed after keying in username and password.

期望的事件:

Screen transit to the home page. Besides having a logout button in home page, username provided earlier is also shown.

我尝试了两种方法:

方法 1:在用户库中创建一个 getusername() class

方法二:在userrepo中赋值class,通过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

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

错误代码:

小部件库捕获异常 以下断言被抛出构建主页(脏): BlocProvider.of() 使用不包含 LoginBloc 类型的 Bloc 的上下文调用。 从传递给的上下文开始找不到祖先 BlocProvider.of()。 如果出现以下情况,就会发生这种情况: 1. 你使用的context来自BlocProvider上面的一个widget。 2. 您使用了 MultiBlocProvider 并且没有明确提供 BlocProvider 类型。

好:BlocProvider(构建器:(上下文)=> LoginBloc()) 错误:BlocProvider(构建器:(上下文)=> LoginBloc())。 使用的上下文是:主页(脏)

我可以通过以下方式解决问题。

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

String getUserName()  {
    return username1;
  }

稍微更改了主页的定义以接受 UserRepository 参数。现在,定义如下所示:

class HomePage extends StatelessWidget {
  final String userName;
  HomePage({Key key, @required this.userName})
      : super(key: key);

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

最后,将 login bloc 行注释为恕我直言,到目前为止,它在您编写的整个主页代码中没有任何有用的内容。新代码:

@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");

这行得通。您将在控制台中看到用户名 window.