Flutter не может объединить RouteAware и панель вкладок - PullRequest
0 голосов
/ 25 февраля 2020

Я не могу использовать RouteAware с панелью вкладок из-за текущей реализации приложения, где я создаю экземпляр GameListScreen без класса Flutter Navigator и не могу наблюдать, когда пользователь возвращается на экран. (см. код ниже). Может кто-нибудь объяснить, пожалуйста, как решить эту проблему? Буду признателен за любую помощь! Спасибо

  class AppBarScreen extends StatefulWidget {
   static const String id = 'GamesListScreen';
   final GlobalKey<ScaffoldState> scaffoldStateKeyContainingDrawer;

   const AppBarScreen({Key key, @required this.scaffoldStateKeyContainingDrawer}) : super(key: key);

  @override
  _AppBarScreenState createState() => _AppBarScreenState();
}

class _AppBarScreenState extends State<AppBarScreen> with SingleTickerProviderStateMixin, RouteAware {
  final Duration appBarAnimationDuration = Duration(milliseconds: 100);
  final double appBarHeight = 50.0;
  int _numberOfTabs = 4;
  bool _isAppBarVisible = true;
  TabController _tabController;
  ScrollController _nestedViewScrollController;
  EventBus _eventBroker = GetIt.instance<EventBus>();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: _numberOfTabs,
      vsync: this,
    );
    _nestedViewScrollController = ScrollController(keepScrollOffset: true);
    _registerToEvents();
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPopNext() {

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).backgroundColor,
      body: NestedScrollView(
          controller: _nestedViewScrollController,
          headerSliverBuilder: (context, value) {
            return [
              buildSliverAppBar(context),
            ];
          },
          body: TabBarView(
            controller: _tabController,
            children: <Widget>[
              BlocProvider(create: (BuildContext context) => GamesListScreenBloc(GamesFetchType.All), child: GameListScreen()),
              BlocProvider(create: (BuildContext context) => GamesListScreenBloc(GamesFetchType.Saved), child: GameListScreen()),
              BlocProvider(create: (BuildContext context) => GamesListScreenBloc(GamesFetchType.AlmostFunded), child: GameListScreen()),
              Text('this is third tab'),
              //_buildLoadingAdditional(),
            ],
          )),
    );
  }

  SliverAppBar buildSliverAppBar(BuildContext context) {
    return SliverAppBar(
      floating: true,
      pinned: true,
      snap: true,
      backgroundColor: Theme.of(context).backgroundColor,
      title: Text(
        AppStrings.GamesTitle,
      ),
      leading: NavigatioNDrawerBuilderWidget(widget.scaffoldStateKeyContainingDrawer),
      bottom: PreferredSize(
        preferredSize: Size.fromHeight(appBarHeight),
        child: TabBar(
          isScrollable: true,
          indicator: UnderlineTabIndicator(
            borderSide: BorderSide(color: AppColors.FAB_PRIMARY_COLOR, width: 2),
            insets: EdgeInsets.symmetric(horizontal: 25, vertical: 10),
          ),
          tabs: <Widget>[
            _buildTab(AppStrings.AllCamapignsTitle),
            _buildTab(AppStrings.SavedGamesTitle),
            _buildTab(AppStrings.AlmostFundedGamesTitle),
            _buildTab(AppStrings.PassedGamesTitle),
          ],
          controller: _tabController,
        ),
      ),
    );
  }

  Tab _buildTab(String title) {
    return Tab(
      child: Text(
        title,
        style: AppFontStyles.kGameListTileSize13WhiteColorTextStyle,
      ),
    );
  }

  void _registerToEvents() {
    _eventBroker.on<ScrollUpEvent>().listen((event) {
      if (!_isAppBarVisible) {
        _showAppBar();
        _isAppBarVisible = true;
      }
    });
    _eventBroker.on<ScrollDownEvent>().listen((event) {
      if (_isAppBarVisible) {
        if (_nestedViewScrollController.hasClients) {
          _hideAppBar();
          _isAppBarVisible = false;
        }
      }
    });
  }

  void _hideAppBar() {
    _nestedViewScrollController.animateTo(appBarHeight, duration: appBarAnimationDuration, curve: Curves.linear);
  }

  void _showAppBar() {
    _nestedViewScrollController.animateTo(0, duration: appBarAnimationDuration, curve: Curves.linear);
  }
}
...