Home > Net >  Calling setState in Flutter TabBar onTap not working
Calling setState in Flutter TabBar onTap not working

Time:11-20

See the attached sample code. If I clear the state when changing tabs by using TabBar onTap, the updated state is not reflected in the TabBarViews.

In my sample code, clicking on the buttons in the TabBarViews sets state which highlights the button. When changing tabs, the buttons in the tabs should no longer be highlighted, but they still are.

import 'package:flutter/material.dart';

void main() {
  runApp(const TabBarDemo());
}

class TabBarDemo extends StatefulWidget {
  const TabBarDemo({super.key});

  @override
  State<TabBarDemo> createState() => _TabBarDemoState();
}

class _TabBarDemoState extends State<TabBarDemo> {
  int state = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: const [
                Tab(text: 'One'),
                Tab(text: 'Two'),
              ],
              onTap: (value) {
                setState(() => state = 0);
              },
            ),
            title: const Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Center(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: (state == 1) ? Colors.blue : Colors.grey,
                  ),
                  onPressed: () {
                    setState(() => state = 1);
                  },
                  child: const Text('One'),
                ),
              ),
              Center(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: (state == 2) ? Colors.blue : Colors.grey,
                  ),
                  onPressed: () {
                    setState(() => state = 2);
                  },
                  child: const Text('Two'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

Actually, this was an issue that has been recently fixed by the flutter team. You can have a look at it enter image description here

CodePudding user response:

Instead of this

  class _TabBarDemoState extends State<TabBarDemo>{
    
    }

Use this :

class _TabBarDemoState extends State<Products> with TickerProviderStateMixin {
  late TabController _tabController;

  void initState() {
    super.initState();

    _tabController = TabController(
      vsync: this,
      length: 0,
      initialIndex: 0,
    );
  }

Now Assign the Controller into Your View then it will work

  • Related