Flutter Dart:BLoC模式可在两个不同的StreamBuilder中更新数据

问题描述

编辑:张贴了我的登录表格。

在“使用电子邮件和密码登录/注册”屏幕上,我有一个Scaffold一个AppBar一个body: List<Widget> FormColumn,后者在一个单独的文件中并被导入。

在我的表单文件中,我让StreamBuilder监听包含数据的块和一个FlatButton,该StreamBuilder将表单逻辑从登录逻辑切换为注册逻辑,请参见如下图所示,我在脚手架上做了第二个class SignInDialog extends StatefulWidget { final EmailPwSignBloc bloc; const SignInDialog({Key key,@required this.bloc}) : super(key: key); // this is my static function // it builds the screen // used 'makeScreenWithbloc' because create is already // used in this file static Widget makeScreenWithbloc(BuildContext context){ AuthService authService = Provider.of<AuthService>(context); return Provider<EmailPwSignBloc>( create: (context) => EmailPwSignBloc(authService: authService),dispose: (context,bloc) => bloc.dispose(),child: Consumer<EmailPwSignBloc>(builder: (context,blocFromProvider,_) => SignInDialog(bloc: blocFromProvider,)),); } static void create(BuildContext context){ // ADDING STATE TO THE APPBAR } @override _SignInDialogState createState() => _SignInDialogState(); } class _SignInDialogState extends State<SignInDialog> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: StreamBuilder<EmailSignInModel>( stream: widget.bloc.getEmailSignInModel,initialData: EmailSignInModel(),builder: (context,snapshot) { final EmailSignInModel data = snapshot.data; return Text(data.appBarText); } ),// Todo: Bool SignIn/Register centerTitle: true),body: Container( child: SingleChildScrollView( child: Padding( padding: EdgeInsets.all(15),child: Card( child: SignInFormBlocCompatible.create(context),) ),); } } ,如下所示:

class SignInFormBlocCompatible extends StatefulWidget
    with EmailAndPasswordStringValidator {
  final EmailPwSignBloc bloc;

  SignInFormBlocCompatible({
    Key key,@required this.bloc,}) : super(key: key);

  static Widget create(context) {
    AuthService authService = Provider.of<AuthService>(context);
    return Provider<EmailPwSignBloc>(
      create: (context) => EmailPwSignBloc(authService: authService),child: Consumer<EmailPwSignBloc>(
        builder: (context,bloc,_) => SignInFormBlocCompatible(bloc: bloc),),);
  }

  @override
  _SignInFormState createState() => _SignInFormState();
}

class _SignInFormState extends State<SignInFormBlocCompatible> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<EmailSignInModel>(
      stream: widget.bloc.getEmailSignInModel,snapshot) {
        final EmailSignInModel model = snapshot.data;
        return Padding(
          padding: const EdgeInsets.fromLTRB(15,30,15,15),child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,mainAxisSize: MainAxisSize.min,children: _listofFormElements(model),);
      }
    );
  }
  static TextEditingController _emailController = TextEditingController();
  static TextEditingController _passwordController = TextEditingController();

  // creating the submit function
  Future<void> _submit(EmailSignInModel model) async {
    // if it is on sign in use sign in function ELSE use register function
    try {
      await widget.bloc.submit();
      Navigator.pop(context);
    } on PlatformException catch (e) {
      print(e.toString());
    } 
  }

  List<Widget> _listofFormElements(EmailSignInModel model) {
   Login_or_reg defaultType = model.loginorReg;
    // validating button text
    var validatingButtonText =
        defaultType == Login_or_reg.signIn ? 'Log In' : 'Create Account';

    // switch between login or register button
    var switchLoginorRegisterText = defaultType == Login_or_reg.signIn
        ? "Don't have an account? Register"
        : 'Have an account? Log in';

    // this function is used to switch between function
    // when switching it clears the fields of text
    void _signInorReg(model) {
        model.loginorReg == Login_or_reg.signIn ? widget.bloc.updateModel(email: '',password: '',submitted: false,appBarText: 'Register',loginorReg: Login_or_reg.register): widget.bloc.updateModel(email: '',appBarText: 'Log In',loginorReg: Login_or_reg.signIn);
        _emailController.clear();
        _passwordController.clear();
    }

    return [
      // email
      TextFormField(
          autocorrect: false,controller: _emailController,onChanged: (value) => widget.bloc.updateModel(email: value),decoration: Inputdecoration(
            enabled: model.enabled == true,hintText: 'example@example.com',labelText: 'eMail',SizedBox(height: 10),// password
      TextFormField(
          autocorrect: false,onChanged: (value) => widget.bloc.updateModel(password: value),controller: _passwordController,obscureText: true,onEditingComplete: () => _submit(model),decoration: Inputdecoration(
            hintText: 'Your password here',labelText: 'Password',SizedBox(height: 20),// my sign in/register button
      CustomFlatButton(
        text: validatingButtonText,color: Colors.indigo,textColor: Colors.white,// my bool signin/register button
      CustomFlatButton(
        text: switchLoginorRegisterText,color: Color(0xff),callback: model.enabled ? () => _signInorReg(model) : null,textColor: Colors.indigo,)
    ];
  }
}

为了能够更新 appBar标题

这是登录表单:

class EmailPwSignBloc {
  final AuthService authService;
  EmailPwSignBloc({@required this.authService});

  StreamController<EmailSignInModel> _streamController =
      StreamController<EmailSignInModel>();

  // GETTER
  Stream<EmailSignInModel> get getEmailSignInModel => _streamController.stream;
  // SETTER
  set _setEmailSignInModel(EmailSignInModel model) =>
      _streamController.sink.add(model);
  EmailSignInModel _modelInstance = EmailSignInModel();
  void dispose() {
    _streamController.close();
  }

  // changing model values
  void updateModel({
    String email,String password,Login_or_reg loginorReg,String appBarText,bool submitted,bool enabled,}) {
    // updating model
    _modelInstance = _modelInstance.copyWith(
      email: email,password: password,appBarText: appBarText,loginorReg: loginorReg,submitted: submitted,enabled: enabled,);
    _setEmailSignInModel = _modelInstance;
  }

  Future<void> submit() async {
    updateModel(submitted: true,enabled: false);
    // if it is on sign in use sign in function ELSE use register function
    try {
      if (_modelInstance.loginorReg == Login_or_reg.signIn) {
        await authService.signInWithEmail(
            _modelInstance.email,_modelInstance.password);
      } else {
        await authService.registerWithEmail(
            _modelInstance.email,_modelInstance.password);
      }
    } catch (e) {
      print('Error occurred and rethrown.');  
      print(e.toString());
      rethrow;
    } finally {
      updateModel(enabled: true);
    }
  }

这是我在集团中的登录

enum Login_or_reg {
  signIn,register,}

class EmailSignInModel {
  final String email;
  final String password;
  final String appBarText;
  final Login_or_reg loginorReg;
  final bool submitted;
  final bool enabled;

  EmailSignInModel({
    this.email = '',this.password = '',this.appBarText = 'Log In',// Todo: change default appBar text 
    this.loginorReg = Login_or_reg.signIn,this.submitted = false,this.enabled = true,});

  EmailSignInModel copyWith({
    String email,}) {
    // Todo: Take off leText & print 
    String leText;
    leText = appBarText ?? this.appBarText;
    print(leText);
    return EmailSignInModel(
      email: email ?? this.email,password: password ?? this.password,appBarText: appBarText ?? this.appBarText,enabled: enabled ?? this.enabled,submitted: submitted ?? this.submitted,loginorReg: loginorReg ?? this.loginorReg,);
  }
}

这是我的登录模型:

arm-linux-gnueabihf-as -o testas.o testas.s
arm-linux-gnueabihf-gcc -o testas testas.o

问题:除AppBar标题外,其他所有东西都正常运行。我在执行中做错了吗?

Loginc/Register Screen

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)