TextField焦点/焦点不集中会强制重新创建我的BloC

时间:2018-10-16 14:15:59

标签: dart flutter

我有以下设置:

class PagesContainer extends StatelessWidget{
final PageController _pCont = PageController();
  @override
  Widget build(BuildContext context) {

    return BlocProvider(
      bloc:ExampleBloc(),
          child: PageView(
          // physics: NeverScrollableScrollPhysics(),
          controller: _pCont,
          children: [
            Screen1(),
            Screen2(),
          ]),
    );
  }}

class ExampleBloc extends Bloc{
ExampleBloc(){
  print('Bloc is initialized');
}

  @override
  void dispose() {
    // TODO: implement dispose
  }

}


class Screen1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final bloc = BlocProvider.of<ExampleBloc>(context);
    return Scaffold(
      body: TextField()
    );
  }
}

class Screen2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}

问题是每当我单击以对TextField中的Screen1进行聚焦/取消聚焦时,整个小部件树都将重新呈现,从而导致重新创建我的ExampleBloc而且我可以看到print('Bloc is initialized');在每个焦点/非焦点事件上一次又一次地执行。我怎样才能防止集团的这种重新出现?

1 个答案:

答案 0 :(得分:0)

Rémi的帮助下,对PageContainer的这一更改解决了我的问题:

Reference answer can be found here for more elaboration

class PagesContainerState extends State<PagesContainer> {
  ExampleBloc _bloc;

final PageController _pCont = PageController();
@override
  void initState() {
    _bloc=ExampleBloc();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {

    return BlocProvider(
      bloc:_bloc,
          child: PageView(
          // physics: NeverScrollableScrollPhysics(),
          controller: _pCont,
          children: [
            Screen1(),
            Screen2(),
          ]),
    );
  }}