简体   繁体   中英

Flutter: How to show the first TabBar/TabBarView when returning to page?

Please view this Demo app . It has a Cupertino bottom navigation bar and on two tabs on the Products page. I've provided code snippets below (note: code mostly adapted from official docs).

My question
When ANY BottomNavigationBarItem item is tapped (whether it's Products, Search, or Cart), I want the index of the tab controller on the Products page to be reset to 0 and setState called on that page. How do I achieve that?

What I'm trying to achieve

  1. When on the Products page, if I select the Right tab (tab index = 1), I want to be able to navigate back to the Left tab (tab index = 0) also by tapping on Products in the bottom navigation.
  2. When on the Products page, if I select the Right tab (tab index = 1), then navigate to a different page (Search page or Cart page), then return to the Products page, I want the Left tab (tab index = 0) to be displayed by default.

Hope this makes sense. Thanks!

(Disclaimer: I'm new to both development and Stackoverflow, so I hope my question is phrased correctly. I'll be sure to amend it as I get relevant feedback).

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'products_page.dart';
import 'search_page.dart';
import 'cart_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo app',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      tabBar: CupertinoTabBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.home),
            title: Text('Products'),
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.search),
            title: Text('Search'),
          ),
          BottomNavigationBarItem(
            icon: Icon(CupertinoIcons.shopping_cart),
            title: Text('Cart'),
          ),
        ],
      ),
      tabBuilder: (context, index) {
        CupertinoTabView returnValue;
        switch (index) {
          case 0:
            returnValue = CupertinoTabView(builder: (context) {
              return CupertinoPageScaffold(
                child: ProductsPage(),
              );
            });
            break;
          case 1:
            returnValue = CupertinoTabView(builder: (context) {
              return CupertinoPageScaffold(
                child: SearchPage(),
              );
            });
            break;
          case 2:
            returnValue = CupertinoTabView(builder: (context) {
              return CupertinoPageScaffold(
                child: CartPage(),
              );
            });
            break;
        }
        return returnValue;
      },
    );
  }
}

products_page.dart

import 'package:flutter/material.dart';

class ProductsPage extends StatefulWidget {

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

class _ProductsPageState extends State<ProductsPage> with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: 2);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              floating: false,
              pinned: true,
              flexibleSpace: FlexibleSpaceBar(
                centerTitle: true,
                title: Text('Products'),
              ),
            ),
            SliverPersistentHeader(
              delegate: _SliverAppBarDelegate(
                TabBar(
                  controller: _tabController,
                  labelColor: Colors.black87,
                  unselectedLabelColor: Colors.grey,
                  tabs: [
                    Tab(text: 'LEFT'),
                    Tab(text: 'RIGHT'),
                  ],
                  // controller:,
                ),
              ),
              pinned: true,
            ),
          ];
        },
        body: TabBarView(
          controller: _tabController,
          children: <Widget>[
            Center(child: Text('This is the left tab', style: TextStyle(fontSize: 30))),
            Center(child: Text('This is the right tab', style: TextStyle(fontSize: 30))),
          ],
        ),
      ),
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate(this._tabBar);

  final TabBar _tabBar;

  @override
  double get minExtent => _tabBar.preferredSize.height;
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return false;
  }
}

Try this, always set initialIndex to 0:

DefaultTabController(
        initialIndex: 0,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM