简体   繁体   中英

Flutter TabBar/TabBarView showing wrong child

I'm working in a flutter app. I have a bottom bar with six children. Two of them are TabBar Screens but I have an issue with them. Any time I change the selected Tab in the TabBar/TabBarView and move to other Screen in the bottom bar navigation and return to the previous Screen with the Tabs the TabBarView shows the last selected tab.

With code:

return SafeArea(

  child: DefaultTabController(
      length: 4,
      initialIndex: 0,
      key: widget.key,
      child: Scaffold(
        //backgroundColor: Colors.white,
        appBar: ColoredTabBar(
          color: Theme.of(context).primaryColorLight,
          tabBar: TabBar(
            unselectedLabelStyle: TextStyle(fontSize: textSize*0.8),
            indicator: BoxDecoration(
              borderRadius: BorderRadius.only(topLeft: Radius.circular(00),topRight: Radius.circular(00)),
              color: Theme.of(context).primaryColor,
              //border: Border.all(),
            ),
            //isScrollable: true,
            labelStyle: TextStyle(fontSize: textSize),
            unselectedLabelColor: Theme.of(context).textTheme.body1.color,
            labelColor: Theme.of(context).unselectedWidgetColor,




            tabs: [
              Tab(text: "Paquetes"),
              Tab(text: "Micro"),
              Tab(text: "Recargas"),
              Tab(text: "A la medida"),
            ],
          ),
          mywalletResponse: widget.wallet,
          numero: widget.defaultNumber,
          onPressed: widget.onPressed,
          onTap: widget.onTap,


        ),
        body:  TabBarView(
          //controller: _tabController2,
          key: widget.key,
          children: [
            CombosScreen(),
            MicroScreen(),
            RecargasScreen(),
            CustomScreen(), // tercera pagina: notificaciones
          ],
        ),
      )))     
;

ColoredTabBar widget is:

    class ColoredTabBar extends Container implements PreferredSizeWidget{
  ColoredTabBar({@required this.color, @required this.tabBar, @required this.mywalletResponse, @required this.numero, @required this.onTap, @required this.onPressed});

  final Color color;
  final TabBar tabBar;
  final WalletResponse mywalletResponse;
  final String numero;
  final VoidCallback onTap;
  final VoidCallback onPressed;





  @override
  Size get preferredSize => Size.fromHeight(103.0);

  @override
  Widget build(BuildContext context) => Container(

      color: color,
      child: Column(
        children: <Widget>[
          Header(number: numero, walletModel: mywalletResponse, onTap: onTap, onPressed: onPressed,),
          tabBar,
        ],
      )

  );
}

So for example, I go to the Widget with the defaultTabController and select the widget at index 2, later I move to another widget in the bottom navigation bar and later I return to the previous widget with the defaultTabController. The selected tab is the one at index 0, but the TabBarView shows the widget at index 2.

Do you know how to initialize the index in a way that the tab and the widget is the same?

You have to save your last tab index and once you redirected to your tab view screen then re-set the value of tab index via TabController .

Lets use TabBarView instead DefaultTabController which works with TabController

class _Page {
  _Page({this.widget});
  final Widget widget;
}

List<_Page> _allPages;

class Home extends StatefulWidget {

    @override
    _HomeState createState() => new _HomeState();


    changeTabIndex(int index) {
        _HomeState()._controller.animateTo(index);
    }
}

class _HomeState extends State<Home> with TickerProviderStateMixin {

    TabController _controller;
    _HomeState();

    @override
    void initState() {
        super.initState();

        _allPages = <_Page>[
            _Page(widget: CombosScreen()),
            _Page(widget: MicroScreen()),
            _Page(widget: RecargasScreen()),
            _Page(widget: CustomScreen()),
        ];

        _controller = TabController(vsync: this, length: 4);
        _controller.addListener(_handleTabSelection);
    }

    _handleTabSelection() { // <--- Save your tab index
        if(_controller.indexIsChanging) {
            // Save your tab index here
            // You can use static variable or BloC state
        }
    }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: TabBarView(
            controller: _controller,
            children: _allPages.map<Widget>((_Page page){
              return SafeArea(
                child: Container(
                    key: ObjectKey(page.widget),
                    child: page.widget
                ),
              );
            }).toList(),
        )
    )
}

And then just call

Home.changeTabIndex(yourLastTabIndex);

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