0

Root widget of the app route

@override
  Widget build(BuildContext context) {
    return SafeArea(
      child: MyStatefulWidget(),
    );
  }

In the inner stateful widget I have text field with focus management. FocusNode disposed in dispose() callback. And finally - if keyboard is opened - all screen rebuilts, and my stateful widget also fully rebuilts with state. Dispose called and keyboard dissapears because of focus node disposed.

My conclusion - all controllers must be provided from route's root widget, because only root widget lives all time without recreate. This is very strange and inconvenient - I can't has self managed widgets and must provide all controlles from outside? If it is true, then how animations, text fields and other widget works? This is mean every rebuild cause state recreation and all animations, etc will stop on rebuild?.. Or there is way to save state between widget recreation? Save state and restore (like android parcelable) between recreation?

Nickolay Savchenko
  • 1,474
  • 16
  • 28
  • This question should be improved to be helpful for others. Specifically more focus and [repro]. Community members please use "flag"/"close" votes to improve this question. – Alex.F Nov 16 '20 at 08:37
  • The point of the state is to survive a rebuild. Could you post some code and what you do, what happens and what you instead expect to happen? – nvoigt Nov 16 '20 at 08:37
  • I don't see how this is an unusual behavior. Aren't you setting the [focusNode](https://flutter.dev/docs/cookbook/forms/focus) in initState() method? – Joy Terence Nov 16 '20 at 08:53
  • Hmm. In other place of my project the same code works normally - dispose not called between widget recreations. One difference that problematic widget placed inside Tab. So this may cause other behaviour and widget always disposes on recreation... – Nickolay Savchenko Nov 16 '20 at 08:58
  • @Alex.F in short words: simple StatefulWidget disposes on every build of its parent. Parent placed into TabBarView - maybe its important. I can't find docs about lifecycle of State. When and why flutter decides to dispose or preserve state. – Nickolay Savchenko Nov 16 '20 at 09:05

2 Answers2

2

Please try, use AutomaticKeepAliveClientMixin mixin, this mixin rebuild from old widget.

Detail visit: https://medium.com/@diegoveloper/flutter-persistent-tab-bars-a26220d322bc

Wisnu Saputra
  • 101
  • 1
  • 7
1

I found my problem: Scaffold has GlobalKey which created in StatefulWidget instead State. And all tree with states was recreated on every rebuild:)

Nickolay Savchenko
  • 1,474
  • 16
  • 28