首页 > 解决方案 > Flutter:使用底部导航栏为应用栏颜色设置动画

问题描述

我不会像底部导航栏对 shift 类型一样为我的 appbar 颜色设置动画。所以 appbar 和 bottomnavigationbar 一起改变颜色。

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  int _tabIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Dash')),
      body: Container(),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _tabIndex,
        onTap: (value) => setState(() => _tabIndex = value),
          type: BottomNavigationBarType.shifting,
          unselectedItemColor: Theme.of(context).unselectedWidgetColor,
          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.dashboard), title: Text('Dash'), backgroundColor: Colors.blue),
            BottomNavigationBarItem(
                icon: Icon(Icons.insert_chart), title: Text('Data'), backgroundColor: Colors.red),
            BottomNavigationBarItem(
                icon: Icon(Icons.monetization_on), title: Text('Income'), backgroundColor: Colors.orange),
          ]),
    );
  }
}

我怎样才能做到这一点?(我对扑腾还很陌生)谢谢!

标签: flutterflutter-animation

解决方案


这很简单。只需根据所选索引更改颜色。

干得好

   import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _tabIndex = 0;
  var colors = [Colors.blue, Colors.red, Colors.orange];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dash'),
        backgroundColor: colors[_tabIndex],
      ),
      body: Container(),
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _tabIndex,
          onTap: (value) => setState(() => _tabIndex = value),
          type: BottomNavigationBarType.shifting,
          unselectedItemColor: Theme.of(context).unselectedWidgetColor,
          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.dashboard),
                title: Text('Dash'),
                backgroundColor: colors[0]),
            BottomNavigationBarItem(
                icon: Icon(Icons.insert_chart),
                title: Text('Data'),
                backgroundColor: colors[1]),
            BottomNavigationBarItem(
                icon: Icon(Icons.monetization_on),
                title: Text('Income'),
                backgroundColor: colors[2]),
          ]),
    );
  }
}

在此处查看现场演示。


推荐阅读