0

I have the following setup:

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

The problem is whenever I click to focus/unfocus the TextField in Screen1 the whole widget tree is re-rendered causing my ExampleBloc to be recreated and I can see print('Bloc is initialized'); executed again and again on each focus/unfocus event. How can I prevent this recreation of the bloc from happening?

Shady Aziza
  • 50,824
  • 20
  • 115
  • 113

1 Answers1

0

With the help of Rémi, this change to PageContainer solved my problem:

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(),
          ]),
    );
  }}
Shady Aziza
  • 50,824
  • 20
  • 115
  • 113