热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Flutter中为底部导航栏图标提供渐变

如何解决《如何在Flutter中为底部导航栏图标提供渐变》经验,为你挑选了1个好方法。

我有一个带有四个图标的底部导航栏,默认颜色是我的应用程序的主题颜色(主色)。我想将选定的图标更改为渐变色,所以我写了一个带有装饰的容器,但是没有任何人可以帮我解决这个问题,它应该如图所示。谢谢

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:material_search/material_search.dart';
import 'dart:ui' as ui;


class DrawerItem {
  String title;
  IconData icon;
  DrawerItem(this.title, this.icon);
}


class HomeScreen extends StatefulWidget {

  final drawerItems = [
    new DrawerItem("Dashboard", Icons.dashboard),
    new DrawerItem("Live Tracking", Icons.track_changes),
    new DrawerItem("Notifications", Icons.notifications),
    new DrawerItem("Account Details", Icons.exit_to_app),
    // new DrawerItem("Reports", Icons.dock),
  ];

  @override
  State createState() {
    return new HomeScreenState();
  }
}


class HomeScreenState extends State {

  final GlobalKey _scaffoldKey = new GlobalKey();
  final JsonDecoder _decoder = new JsonDecoder();

  String pageValue = 'Dashboard';

  IconData selectedItem = Icons.dashboard ;
  List itemsList = [
      Icons.dashboard, Icons.location_on, Icons.notifications, Icons.account_circle,
  ];

  //Vehicles Data
  final _vehicleNumbers = [];
  String vehicleNum = '';
  static String _id;
  String value;
  String getValue;
  dynamic vehicleData;
  var vehiclesLength = 0;
  var addVehiclesLength = 0;
  int bottomNavBarIndex = 0;

  Widget appBarTitle = new Text("Dashboard",
    style: TextStyle(
      fontSize: 24.0,
      // fontWeight: FontWeight.bold,
      color: Colors.grey[600]
    ),
    textAlign: TextAlign.center
  );
  bool search = false;

  //UserDetails
  static dynamic user = new User();
  String key = user.getKey();

   int _selectedDrawerIndex = 0;

  _getDrawerItemWidget(int pos) {
    switch (pos) {
      case 0:
        return new Dashboard();
      case 1:
        return new LiveTracking();
      case 2:
        return new Notifications();
      case 3:
        return new AccountProfile();
      default:
        return new Text("Error");
    }
  }

  _onSelectItem(int index) {

    if(widget.drawerItems[_selectedDrawerIndex].title == 'Dashboard'){
      this.appBarTitle = new Text(widget.drawerItems[_selectedDrawerIndex].title,
        style: TextStyle(
          fontSize: 24.0,
          // fontWeight: FontWeight.bold,
          color: Colors.grey[600],
        ),
        textAlign: TextAlign.center
      );
      this.pageValue = widget.drawerItems[_selectedDrawerIndex].title;
    }
    else if(widget.drawerItems[_selectedDrawerIndex].title == 'Live Tracking'){
      this.appBarTitle = new Text(widget.drawerItems[_selectedDrawerIndex].title,
        style: TextStyle(
          fontSize: 24.0,
          // fontWeight: FontWeight.bold,
          color: Colors.grey[600],
        ),
        textAlign: TextAlign.center
      );
      this.pageValue = widget.drawerItems[_selectedDrawerIndex].title;
    }
    else if(widget.drawerItems[_selectedDrawerIndex].title == 'Notifications'){
      this.appBarTitle = new Text(widget.drawerItems[_selectedDrawerIndex].title,
        style: TextStyle(
          fontSize: 24.0,
          // fontWeight: FontWeight.bold,
          color: Colors.grey[600],
        ),
        textAlign: TextAlign.center
      );
      this.pageValue = widget.drawerItems[_selectedDrawerIndex].title;
    }
    else if(widget.drawerItems[_selectedDrawerIndex].title == 'Account Details'){
      this.appBarTitle = new Text(widget.drawerItems[_selectedDrawerIndex].title,
        style: TextStyle(
          fontSize: 24.0,
          // fontWeight: FontWeight.bold,
          color: Colors.grey[600],
        ),
        textAlign: TextAlign.center
      );
      this.pageValue = widget.drawerItems[_selectedDrawerIndex].title;
    }
  } 

  //Vehicle List Data
  Future getVehiclesData() async {
    var respOnse= await http.get(
        Uri.encodeFull(API.dashboardData),
        headers: {HttpHeaders.AUTHORIZATION: "Basic " + key});
    final String res = response.body;
    vehicleData = _decoder.convert(res);
    vehiclesLength = vehicleData["_items"].length;

    setState(() {
      addVehiclesLength =  vehiclesLength;
      for(int i=0;i(
      settings: new RouteSettings(
        name: 'material_search',
        isInitialRoute: false,
      ),
      builder: (BuildContext context) {
        return new Material(
          child: new MaterialSearch(
            placeholder: 'Search',
            results: _vehicleNumbers.map((getValue) => new MaterialSearchResult(
              value: getValue,
              text: "$getValue",
            )).toList(),
            filter: (dynamic value, String criteria) {
              return value.toLowerCase().trim()
                .contains(new RegExp(r'' + criteria.toLowerCase().trim() + ''));
            },
            onSelect: (dynamic value) => Navigator.of(context).pop(value),
          ),
        );
      }
    );
  }




  //Logout functionality... 
  void _logout() async {
    var db = new DatabaseHelper();
    await db.deleteUsers();
  }


  //To initiate state of the class before loading that paticular page...
  @override
  void initState() {
    super.initState();
    print('came to init state');
    getVehiclesData();
  }

  _showMaterialSearch(BuildContext context) {
    if(pageValue != null && pageValue == 'Dashboard'){
    Navigator.of(context)
      .push(_buildMaterialSearchPage(context))
      .then((dynamic value) {
        setState(() => vehicleNum = value as String);
        String check = vehicleNum;
        // print('check = $check');
        if(check != '' && check != null){
          check = '';
          _id = _getId(vehicleNum);
          print(_id);
          Navigator.push(context, new MaterialPageRoute(builder: (context) => new SingleVehicleDashboard(value:_id)));
        }
      });
    }
    else if(pageValue != null && pageValue == 'Live Tracking'){
    Navigator.of(context)
      .push(_buildMaterialSearchPage(context))
      .then((dynamic value) {
        setState(() => vehicleNum = value as String);
        String check = vehicleNum;
        // print('check = $check');
        if(check != '' && check != null){
          check = '';
          _id = _getId(vehicleNum);
          print(_id);
          Navigator.push(context, new MaterialPageRoute(builder: (context) => new SingleVehicleDashboard(value:_id)));
        }
      });
    } 
  }

  String _getId(String vehicleNum){
    String id;
    for(int i=0;i[
          widget.drawerItems[_selectedDrawerIndex].title == 'Dashboard' || widget.drawerItems[_selectedDrawerIndex].title == 'Live Tracking' ?
          new IconButton(
            onPressed: () {
              search = true;
              _showMaterialSearch(context);
            },
            tooltip: 'Search',
            icon: new Icon(Icons.search),
          ) : new Text(''),
          widget.drawerItems[_selectedDrawerIndex].title == 'Account Details' ?
          new IconButton(
            onPressed: () {
              _logout();
              Navigator.of(context).pushReplacementNamed("/login");
            },
            tooltip: 'Search',
            icon: new Icon(Icons.exit_to_app),
          ) : new Text(''),
          widget.drawerItems[_selectedDrawerIndex].title == 'Notifications' ?
          new Text(''):new Text('')
        ],
        elevation:
        widget.drawerItems[_selectedDrawerIndex].title == 'Notifications' ?
        2.0:0.0,
      ),

      bottomNavigationBar: BottomNavigationBar(
        currentIndex: bottomNavBarIndex,
        onTap: (int index) {
          setState(() {
            bottomNavBarIndex = index;
            _selectedDrawerIndex = index;
            _onSelectItem(index);
            selectedItem = itemsList[index];
            print(index);
          });
        },
        items: itemsList.map((data) {
          return BottomNavigationBarItem(
            icon: selectedItem == data ? ShaderMask(
              blendMode: BlendMode.srcIn,
              shaderCallback: (Rect bounds) {
                return ui.Gradient.linear(
                  Offset(4.0, 24.0),
                  Offset(24.0, 4.0),
                  [Colors.greenAccent[200],Colors.blueAccent[200]]
                );
              },
              child: Icon(data),
              ) : Icon(data, color: Colors.grey[600]),
              title: Container(),
            );
          }).toList()
        ),


      // bottomNavigationBar: new BottomAppBar(
      //   child: BottomNavigationBar(
      //     currentIndex: bottomNavBarIndex,
      //     onTap: (int index){
      //       setState(() {
      //         bottomNavBarIndex = index;
      //         _selectedDrawerIndex = index;
      //         _onSelectItem(index);
      //       });
      //     },
      //     items: 
      //     [
      //       BottomNavigationBarItem(
      //         icon: new Icon(Icons.dashboard),
      //         title: new Text(''),
      //       ),
      //       BottomNavigationBarItem(
      //         icon: new Icon(Icons.location_on),
      //         title: new Text(''),
      //       ),
      //       BottomNavigationBarItem(
      //         icon: new Icon(Icons.notifications),
      //         title: new Text(''),
      //       ),
      //       BottomNavigationBarItem(
      //         icon: new Icon(Icons.account_circle),
      //         title: new Text(''),
      //       ),
      //     ],
      //   ),
      // ),  
      // endDrawer: new Drawer(
      //     child: Column(
      //       children: [
      //         new Text(
      //           '',
      //           style: new TextStyle(
      //             fontSize: 30.0,
      //             fontWeight: FontWeight.bold,
      //           ),
      //           textAlign: TextAlign.center,
      //         ),
      //         new Text(
      //           'Notifications',
      //           style: new TextStyle(
      //             fontSize: 24.0,
      //             fontWeight: FontWeight.bold,
      //           ),
      //           textAlign: TextAlign.center,
      //         ),
      //         Flexible(
                // child: ListView(
                //   children: List.generate(notificationsLength,
                //     (i) => new Container(
                //       decoration: new BoxDecoration(
                //         border: new Border(
                //             bottom: BorderSide(
                //       color: Colors.grey[300],
                //     ))),
                //       height: 100.0,
                //       padding: EdgeInsets.fromLTRB(8.0, 5.0, 8.0, 5.0),
                //       child: new Text(
                //         addNotifications["_items"][i]["alert_message"],
                //         style: new TextStyle(fontSize: 14.0),
                //       ),
                //     )),
                // ),
      //         )
      //       ],
      //     ),
      //   ),
      body: new Center(
        child:_getDrawerItemWidget(_selectedDrawerIndex),
      ),
    );
  }
}

我想这样显示我的底部导航栏。

这就是我现在所拥有的...



1> anmol.majhai..:

可以在-ShaderMask的帮助下实现您想要的东西,您可以在“各种渐变”下玩,并实现您真正想要的东西。例如,检查以下代码:

bottomNavigationBar: BottomNavigationBar(
        currentIndex: bottomNavBarIndex,
        onTap: (int index) {
          setState(() {
            bottomNavBarIndex = index;
            _selectedDrawerIndex = index;
            _onSelectItem(index);
          });
        },
        items: [
          BottomNavigationBarItem(
            activeIcon: ShaderMask(
              shaderCallback: (Rect bounds) {
                return RadialGradient(
                  center: Alignment.topLeft,
                  radius: 0.5,
                  colors: [
                    Colors.greenAccent[200],
                    Colors.blueAccent[200]
                  ],
                  tileMode: TileMode.repeated,
                ).createShader(bounds);
              },
              child: Icon(Icons.dashboard),
            ),
            icon: new Icon(Icons.dashboard, color: Colors.grey),
            title: new Text(''),
          ),
          BottomNavigationBarItem(
            activeIcon: ShaderMask(
              shaderCallback: (Rect bounds) {
                return RadialGradient(
                  center: Alignment.topLeft,
                  radius: 1.0,
                  colors: [
                    Colors.greenAccent[200],
                    Colors.blueAccent[200]
                  ],
                  tileMode: TileMode.mirror,
                ).createShader(bounds);
              },
              child: Icon(Icons.location_on),
            ),
            icon: Icon(Icons.location_on, color: Colors.grey),
            title: new Text(''),
          ),
          BottomNavigationBarItem(
            activeIcon: ShaderMask(
              shaderCallback: (Rect bounds) {
                return RadialGradient(
                  center: Alignment.topLeft,
                  radius: 1.0,
                  colors: [
                    Colors.greenAccent[200],
                    Colors.blueAccent[200]
                  ],
                  tileMode: TileMode.mirror,
                ).createShader(bounds);
              },
              child: Icon(Icons.notifications),
            ),
            icon: Icon(Icons.notifications, color: Colors.grey),
            title: Text(''),
          ),
          BottomNavigationBarItem(
            activeIcon: ShaderMask(
              shaderCallback: (Rect bounds) {
                return RadialGradient(
                  center: Alignment.topLeft,
                  radius: 1.0,
                  colors: [
                    Colors.greenAccent[200],
                    Colors.blueAccent[200]
                  ],
                  tileMode: TileMode.mirror,
                ).createShader(bounds);
              },
              child: Icon(Icons.account_circle),
            ),
            icon: Icon(Icons.account_circle, color: Colors.grey),
            title: Text(''),
          ),
        ],
      ),


推荐阅读
  • Android自定义控件绘图篇之Paint函数大汇总
    本文介绍了Android自定义控件绘图篇中的Paint函数大汇总,包括重置画笔、设置颜色、设置透明度、设置样式、设置宽度、设置抗锯齿等功能。通过学习这些函数,可以更好地掌握Paint的用法。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • Android JSON基础,音视频开发进阶指南目录
    Array里面的对象数据是有序的,json字符串最外层是方括号的,方括号:[]解析jsonArray代码try{json字符串最外层是 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • 如何查询zone下的表的信息
    本文介绍了如何通过TcaplusDB知识库查询zone下的表的信息。包括请求地址、GET请求参数说明、返回参数说明等内容。通过curl方法发起请求,并提供了请求示例。 ... [详细]
  • 在Android中解析Gson解析json数据是很方便快捷的,可以直接将json数据解析成java对象或者集合。使用Gson解析json成对象时,默认将json里对应字段的值解析到java对象里对应字段的属性里面。然而,当我们自己定义的java对象里的属性名与json里的字段名不一样时,我们可以使用@SerializedName注解来将对象里的属性跟json里字段对应值匹配起来。本文介绍了使用@SerializedName注解解析json数据的方法,并给出了具体的使用示例。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • 图像因存在错误而无法显示 ... [详细]
  • express工程中的json调用方法
    本文介绍了在express工程中如何调用json数据,包括建立app.js文件、创建数据接口以及获取全部数据和typeid为1的数据的方法。 ... [详细]
  • 数据库技术:execute immediate
    首先在这里发发牢骚,指责下那些刻板的书写方式,不考虑读者理不理解,感觉就是给专业人员用来复习用的一样,没有前戏,直接就高潮,实在受不了!没基础或基础差的完全不知道发生了什么,一脸懵 ... [详细]
  • 一维数组与二维数组互相转换一、二维数组转一维数组1.1使用reduce实现vararr1[[1,2],[3,4],[5,6],[7]];func ... [详细]
  • 1.Listener是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。当增加一个HttpSession时 ... [详细]
author-avatar
ggty11
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有