首页 > 解决方案 > Flutter - 多个图标改变了每个图标的颜色

问题描述

我的应用程序底部栏中有 4 个图标,我需要将图标的颜色从灰色更改为白色,我遵循了这个问题,但是当我按下任何图标时,所有图标同时更改颜色,例如按下时我需要(主页)图标只需按(主页)图标。

我怎样才能做到这一点??

以及如何在不按的情况下设置主页图标始终是第一页?(我的意思是当用户打开应用程序时向他显示主页(白色图标))。

代码:

import 'package:flutter/material.dart';

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

class _HomePageState extends State<HomePage> {

  _HomePageState();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  bool isPressed = false;

  _pressed() {
  var newVal = true;
  if(isPressed) {
    newVal = false;
  } else {
    newVal = true;
  }

  setState((){
  isPressed = newVal;
  });
}

@override
Widget build(BuildContext context) {
  return Scaffold(

    appBar: AppBar(
      title: Image.asset('assets/logo.png', fit: BoxFit.cover,),
      centerTitle: true,
      backgroundColor: Colors.grey[900],
    ),
    bottomNavigationBar: BottomAppBar(
      color: Colors.grey[900],
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          IconButton(icon: Icon(Icons.info), color: isPressed ? Colors.white:Colors.grey[600], iconSize: 30, onPressed: () {
          setState(() {
            _pressed();
          });
        }),
          IconButton(icon: Icon(Icons.local_mall), color: isPressed ? Colors.white:Colors.grey[600], iconSize: 30, onPressed: () {
          setState(() {
            _pressed();
          });
        }),
          IconButton(icon: Icon(Icons.bookmark), color: isPressed ? Colors.white:Colors.grey[600], iconSize: 30, onPressed: () {
          setState(() {
            _pressed();
          });
        }),
          IconButton(icon: Icon(Icons.home), color: isPressed ? Colors.white:Colors.grey[600], iconSize: 30, onPressed: () {
          setState(() {
            _pressed();
          });
        }),
      ],
    ),
  ),

);
}
}

标签: androidiosflutterdartcross-platform

解决方案


你可以这样做!!真的是切换图标颜色的最佳技巧

   IconButton( icon:  ImageIcon(AssetImage("images/edit.png",) ,size: 30,),
                            disabledColor: Color.fromRGBO(32, 127, 195, 1),
                            color: Colors.white,
                            onPressed: a == 1
                                ? null
                                : () => setState(() => a = 1)),
 IconButton( icon:   ImageIcon(AssetImage("images/notify.png",) ,size: 30,),
                            disabledColor: Color.fromRGBO(32, 127, 195, 1),
                            color: Colors.white,
                            onPressed: a == 2
                                ? null
                                : () => setState(() {
                                      a = 2;
                                      dateTemp = '';
                                    })),

推荐阅读