【问题标题】:Flutter Bloc Tutorial - How to show user name i.e. value from other pageFlutter Bloc 教程 - 如何显示用户名,即来自其他页面的值
【发布时间】:2019-12-19 01:41:35
【问题描述】:

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

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

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

预期输入:

在登录页面,输入用户名和密码后按下登录按钮。

期望的事件:

屏幕转至主页。除了主页上有注销按钮外,还显示了之前提供的用户名。

我尝试了两种方法:

方法一:在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();
          }
        },
      ),
    );
  }
}

错误代码:

小部件库发现的异常 在构建 HomePage(dirty) 时抛出了以下断言: 使用不包含 LoginBloc 类型的 Bloc 的上下文调用 BlocProvider.of()。 从传递给的上下文开始找不到祖先 BlocProvider.of()。 在以下情况下可能会发生这种情况: 1.您使用的上下文来自 BlocProvider 上方的一个小部件。 2. 您使用了 MultiBlocProvider 并且没有明确提供 BlocProvider 类型。

好:BlocProvider(builder: (context) => LoginBloc()) 不好:BlocProvider(builder: (context) => LoginBloc())。 使用的上下文是:主页(脏)

【问题讨论】:

  • 到目前为止你尝试过什么?请在此处分享代码。
  • 嗨@kiner_shah,感谢您回答我的问题。我已经更新了上面的代码。我尝试了 2 种方法来访问登录表单页面中的方法;方法一:在userrepo类中创建getusername()方法二:在userrepo类中赋值,通过blocprovider访问
  • 登录成功后是否打印用户名?我的意思是HomePage 类中的这一行print("$username2");。
  • 您好 Kiner,这两种方法都不会打印用户名。错误代码似乎指向上下文。我已经更新了上述问题中的错误代码。
  • @kiner_shah 感谢您提供赏金。非常感谢。

标签: flutter dart bloc


【解决方案1】:

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

将 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 行注释为恕我直言,它在您迄今为止编写的整个 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");

这很有效。您将在控制台窗口中看到用户名。

【讨论】:

  • 嗨,Sukhi。感谢您帮助回答。
  • 嗨,Sukhi。谢谢你帮忙解答。是的,使用 key 可以帮助访问变量。但是,从我对 bloc 的有限了解来看,这种方法似乎并没有利用 bloc 框架。您认为可以使用 bloc 从登录页面中获取 username 的值吗?如果是这样,你能告诉我怎么做吗?
  • 只是为了检查您是否碰巧知道如何提取祖先上下文?
  • 我还没有机会与 Bloc 合作。快速浏览了几个教程,这让我认为两个两个是相互独立的,即直接传递有效负载或通过 Bloc。据我了解,Bloc 更多用于事件和状态管理。如果我错了,专家可以纠正我。我提到了:Tutorial 1,Tutorial 2
  • 感谢分享。如果没有人能够在明天之前发布利用 Bloc 框架获取价值的解决方案,我会将您的答案标记为已接受(为了那些不使用 bloc 的人的利益)。另外,我正在探索在登录页面使用多提供商来提供价值。您可能想检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2012-05-28
  • 1970-01-01
  • 2020-11-03
  • 2020-03-26
  • 1970-01-01
  • 2021-08-07
相关资源
最近更新 更多