在LayoutBuilder中使用StreamBuilder时,抖动无限循环

时间:2019-05-10 10:04:10

标签: flutter reactivex bloc rxdart

所以我正在使用 LayoutBuilder 制作页面,如here

所述

在LayoutBuilder中,我放置了一个 StreamBuilder 和一个 TextField ,该类由bloc类 SignupFormBlo c提供支持。流是一个 BehaviorSubject

当有人在输入中添加内容时,它会触发onChanged函数,该函数是我的流的接收器。因此,我将值添加到流中,然后将值传递到 StreamTransformer 中以验证值,然后让StreamBuilder再次生成文本字段,并显示一条错误消息(如果值无效)。

这是问题的开始。

当我单击TextField并输入内容时,它将启动一个无限循环,如下所示:

  • StreamBuilder在流中看到新值
  • StreamBuilder尝试重建TextField
  • 一些如何触发LayoutBuilder构建器功能
  • LayoutBuilder构建器功能再次构建StreamBuilder
  • StreamBuilder在Stream中找到一个值(由于BehaviorSubject)
  • 一切都从无休止的循环中的第一个公牛再次开始

提示::如果我将BehaviorSubject更改为PublishSubject,则一切正常

提示2:如果我完全删除StreamBuilder并只留下一个空白的TextField,则可以看到LayoutBuilder构建器功能在每个条目中都运行。这是正常现象吗?

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {


  SignupFormBloc _signupFormBloc;

  @override
  void initState() {
    super.initState();
    _signupFormBloc = SignupFormBloc();
  }

  @override
  Widget build(BuildContext context) {
    print('Build Run!!!!!');
    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints viewportConstraints) {
          print('Layout Builder!!!');
          return SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: viewportConstraints.maxHeight,
              ),
              child: IntrinsicHeight(
                child:         StreamBuilder<String>(
                  stream: _signupFormBloc.emailStream,
                  builder: (context, AsyncSnapshot<String> snapshot) {

                    return TextField(
                      onChanged: _signupFormBloc.onEmailChange,
                      keyboardType: TextInputType.emailAddress,
                      decoration: InputDecoration(
                        hintText: 'Email',
                        contentPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 18),
                        filled: true,
                        fillColor: Colors.white,
                        errorText: snapshot.error,
                        border: new OutlineInputBorder(
                          borderSide: BorderSide.none
                        ),
                      ),

                    );
                  }
                ),
              ),
            ),
          );
        },
      )
    );
  }

  @override
  void dispose() {
    _signupFormBloc?.dispose();
    super.dispose();
  }

}


class SignupFormBloc  {

  ///
  /// StreamControllers
  ///
  BehaviorSubject<String> _emailController = BehaviorSubject<String>();


  ///
  /// Stream with Validators
  ///
  Observable<String> get emailStream => _emailController.stream.transform(StreamTransformer<String,String>.fromHandlers(handleData: (email, sink){

    final RegExp emailExp = new RegExp(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$");

    if (!emailExp.hasMatch(email) || email.isEmpty){
      print('has error');
      sink.addError('Email format is invalid');
    } else {
      sink.add(email);
    }
  }));


  ///
  /// Sinks
  ///
  Function(String) get onEmailChange => _emailController.sink.add;


  void dispose() {
    _emailController.close();
  }



}

1 个答案:

答案 0 :(得分:3)

发生这种情况是因为滥用了流。

罪魁祸首是这条线:

Observable<String> get emailStream => _emailController.stream.transform(...);

此行的问题是它每次都会创建一个新的流。

这意味着bloc.emailStream == bloc.emailStream实际上是错误的。

StreamBuilder结合使用时,意味着每次有人要求StreamBuilder进行重建时,后者都会从头开始重新启动监听过程。


您应该在BLoC的构造函数主体内创建流一次,而不是使用getter:

class MyBloc {
  StreamController _someController;
  Stream foo;

  MyBloc() {
    foo = _someController.stream.transform(...);
  }
}