我有以下设置:
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');
在每个焦点/非焦点事件上一次又一次地执行。我怎样才能防止集团的这种重新出现?
答案 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(),
]),
);
}}