Home > Blockchain >  Flutter hive clearing box during swiping between tabs
Flutter hive clearing box during swiping between tabs

Time:11-23

In my case we have 3 tabs in TabController and in all of this pages we have some data which we want to use them, now on each tab when we are swiping between them we don't have previous data and length of box values is 0, you suppose we have three tab as:

screen_a
screen_b
screen_c

into screen_a we have:

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() =>MyHome();
}

class MyHome extends State<Home> {
  late Box<Level> _level;
  late List<Level> levels ;
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _level = Hive.box<Level>('level');
    levels = _level.values.toList();
  }
  @override
  Widget build(BuildContext context) {

now on starting application we have many data on screen_a and after swiping on screen_b and going back to screen_a we don't have any data in hive :| :|

what's the problem?

CodePudding user response:

You should store your tabs' data in a bloc or controller class that does not lose state and data when switching between tabs.

CodePudding user response:

It depends on your overall use case and how you want your TabViews to behave, but you can work with the AutomaticKeepAliveClientMixin to ensure that your state of the StatefulWidget stays intact when switching tabs. This also ensures that the content of your StatefulWidget does not have to be rebuild when switching tabs, but will still use resources (just to keep in mind for performance considerations when working with more complex scenarios):

class MyHome extends State<Home> with AutomaticKeepAliveClientMixin {
  /// Here you can either add custom logic to determine when
  /// this tab should be kept "alive" - for now returning [true]
  /// will work out.
  @override
  bool get wantKeepAlive => true;

  ...
  • Related