FlutterでAppBarを変更せずにTabBarの背景色を変更するにはどうすればいいですか? 質問する

FlutterでAppBarを変更せずにTabBarの背景色を変更するにはどうすればいいですか? 質問する

TabBarを変更せずにの背景色を変更するにはどうすればいいですかAppBar? にはプロパティTabBarがありませんがbackground、回避策はありますか?

ベストアンサー1

テーマの primaryColor を次のように変更することで、TabBar の色を変更できます。

return MaterialApp(
      theme: ThemeData(
        brightness: Brightness.light,
      // add tabBarTheme 
      tabBarTheme: const TabBarTheme(
        labelColor: Colors.pink[800],
        labelStyle: TextStyle(color: Colors.pink[800]), // color for text
        indicator: UnderlineTabIndicator( // color for indicator (underline)
          borderSide: BorderSide(color: ConstColor.primary))),
        primaryColor: Colors.pink[800], // outdated and has no effect to Tabbar
        accentColor: Colors.cyan[600] // deprecated,
      ),
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              indicatorColor: Colors.lime,
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );

AppBar で使用していない場合は、次のように TabBar を Material ウィジェットでラップし、色属性を設定できます。

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Tabs Demo'),
        ),
        body: DefaultTabController(
          length: 3,
          child: Column(
            children: <Widget>[
              Container(
                constraints: BoxConstraints(maxHeight: 150.0),
                child: Material(
                  color: Colors.indigo,
                  child: TabBar(
                    tabs: [
                      Tab(icon: Icon(Icons.directions_car)),
                      Tab(icon: Icon(Icons.directions_transit)),
                      Tab(icon: Icon(Icons.directions_bike)),
                    ],
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: [
                    Icon(Icons.directions_car),
                    Icon(Icons.directions_transit),
                    Icon(Icons.directions_bike),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

おすすめ記事