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

标签 flutter dart bloc

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

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

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

预期输入:

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.

我尝试了两种方法:

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

方法二:在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"),**
              ),
            ],
          ),
        ),
      ),
    );
  }
}

用户 repo 类

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

错误代码:

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

好:BlocProvider(构建器:(上下文)=> LoginBloc()) 错误:BlocProvider(构建器:(上下文)=> 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) {
// ...

最后,将 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");

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

关于Flutter Bloc 教程 - 如何显示用户名,即来自其他页面的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57461821/

相关文章:

flutter - 如何修复此错误 Task 'assembleAarRelease' not found in root project 'flutter_plugin_android_lifecycle' .?

flutter - Provider 中是否有任何属性明智的 notifyListerners 选项?

flutter - 如何使用 bloc in flutter 将数据传递到另一个屏幕

server - Flutter:无需等待服务器响应即可处置 Bloc

dart - flutter :未处理的异常:错误状态:调用关闭后无法添加新事件

flutter - 如何在 Flutter 中创建从左到右或从上到下叠加的飞溅动画

flutter - 如何在不同类的 Iterator FOR 中传递变量列表?

dart - Flutter image_picker post上传图片

flutter - 在 Flutter 中将图像添加到 ListTile

class - "unresolved implicit call to super constructor"在 Dart 语言中是什么意思?