【问题标题】:How to change the color of one element not the whole elements?如何改变一个元素的颜色而不是整个元素的颜色?
【发布时间】:2018-09-25 17:37:51
【问题描述】:

我正在制作五个容器,每个容器都包含带有星形图标的 IconButton,我希望星形在按下时切换颜色,我使用了变量 color2,我最初将其设置为等于 Colors.grey它将显示在代码中。但是,问题是当我按下其中一个图标按钮时,所有星星都会改变颜色。这是代码:

  class _MyHomePageState extends State<MyHomePage> {
  bool _star1;
  Color color1 =Colors.grey;
  Color color2=Colors.grey;
List<Meal> list1=[Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat: '20th of september 2018'),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'21th of september 2018'),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'22th of september 2018'),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'23th of september 2018'),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'24th of september 2018')];

 change(){
   setState(() {
   if (color2==Colors.grey){
     color2=Colors.yellow;
   }
   else {
     color2=Colors.grey;
   }
   });
 }

 bool hi(String x){
  if (x!='22th of september 2018'&&x!='20th of september 2018'&&x!='21th of september 2018'){
   _star1 =true;
  }
  else{
    _star1=false;
  }
  return _star1;
}

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('listviewww'),),
      body:
        ListView( children:list1
        .map((element){
          return Column(
            children: <Widget>[
          Container(
              child: Text(element.dat),),
          Container(
           margin: EdgeInsets.all(9.0),
           constraints: new BoxConstraints.expand(height: 300.0),
           decoration: new BoxDecoration(
           border: new Border.all(color: Colors.blueAccent),
           borderRadius: BorderRadius.horizontal( left:Radius.circular(30.0) ,right:Radius.circular(30.0) ),
           image: new DecorationImage(image: new AssetImage('assets/food1.jpg'),fit: BoxFit.cover,),),
           padding: EdgeInsets.only(bottom: 10.0),
      child:Column(
        children:<Widget>[ 
          Row(children: <Widget>[
          Container(
            padding:  EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 80.0),
            alignment: Alignment.topRight,
            child:IconButton(
              onPressed:(){ hi(element.dat)?null:change();},
              icon:Icon(Icons.star),color:color2 ,)),
            Expanded( 
              child: Column(  
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  alignment: Alignment.topCenter,
                  padding: const EdgeInsets.only(bottom: 1.0),
                  child: Text(
                    element.name,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 40.0),),),
               Container(
                margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 90.0),
                child:Text(element.dis,style: TextStyle(color: Colors.grey[800],fontSize: 18.0),),),],), ),
               Container( 
                  padding:  EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 80.0),
                  alignment: Alignment.topLeft,
                  child:IconButton(
                      onPressed:null,
                      icon:Icon(Icons.done_all,color: hi(element.dat)?Colors.grey:Colors.lightBlue,)),),],),],))],);  
        }).toList()));}}

编辑我在类中添加了颜色作为元素,如下所示,但如果我按下任何按钮,颜色不会改变:

List<Meal> list1=[Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat: '20th of september 2018',today:DateTime.now().subtract(Duration(days:2)),butcolor: Colors.grey),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'21th of september 2018',today:DateTime.now().subtract(Duration(days:1)),butcolor: Colors.grey),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'22th of september 2018',today:DateTime.now(),butcolor: Colors.grey),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'23th of september 2018',today: DateTime.now().add(Duration(days:1)),butcolor: Colors.grey),
Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'24th of september 2018',today: DateTime.now().add(Duration(days:2)),butcolor: Colors.grey)];

switchcolor(Color x ){
  setState(() {
if (x==Colors.yellow){
  x=Colors.grey;
}
else{
  x=Colors.yellow;
}
 });
}
child:IconButton(
              onPressed:(){ hi(element.today)?null:switchcolor(element.butcolor);},
              icon:Icon(Icons.star),color:element.butcolor,)),

有什么想法吗? 提前致谢。

【问题讨论】:

  • hi(element.dat) 在做什么?..
  • 请添加更多代码。
  • 如果这一天还没有到来,它返回 true,否则它在过去的日子里返回 false。因为我希望禁用即将到来的日子,因为用户还没有体验到它,所以他无法判断这是否是他的最爱
  • @VirenVVarasadiya 看看新的编辑

标签: button flutter specifications


【解决方案1】:

这里的问题是,每当单击 stat 中的任何一个时,您对所有列表变量(color2)都使用相同的变量,然后 setState 设置适用于所有小部件的第二种颜色,因此您面临这个问题。为避免这种情况,您可以在 list1 的元素中添加颜色属性。并在点击事件上更改该颜色。

  import 'package:flutter/material.dart';

  void main() => runApp(new MyApp());

  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return new MaterialApp(
        title: 'Flutter Demo',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        debugShowCheckedModeBanner: false,
        home: new MyHomePage(),
      );
    }
  }

  class Meal{
    String dis;
    String name;
    String dat;
    Color color = Colors.grey;

    Meal({String name, String dis,String dat,Color color}){
      this.dat = dat;
      this.name = name;
      this.dis = dis;
    }

  }

  class MyHomePage extends StatefulWidget {
    @override
    _MyHomePageState createState() => _MyHomePageState();
  }

  class _MyHomePageState extends State<MyHomePage> {
    bool _star1;
    Color color1 =Colors.grey;
    Color color2=Colors.grey;
    List<Meal> list1=[
      Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat: '20th of september 2018'),
      Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'21th of september 2018'),
      Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'22th of september 2018'),
      Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'23th of september 2018'),
      Meal(dis:'it is a chicken sandwichh',name: 'chekin filla',dat:'24th of september 2018')
    ];

    change(Meal current){
      setState(() {
        if (current.color==Colors.grey){
          current.color=Colors.yellow;
        }
        else {
          current.color=Colors.grey;
        }
      });
    }

    bool hi(String x){
      if (x!='22th of september 2018'&&x!='20th of september 2018'&&x!='21th of september 2018'){
        _star1 =true;
      }
      else{
        _star1=false;
      }
      return _star1;
    }

    @override
    Widget build(BuildContext context) {
      return new Scaffold(
          appBar: new AppBar(
            title: new Text('listviewww'),),
          body:
          ListView( children:list1
              .map((element){
            return Column(
              children: <Widget>[
                Container(
                  child: Text(element.dat),),
                Container(
                    margin: EdgeInsets.all(9.0),
                    constraints: new BoxConstraints.expand(height: 300.0),
                    decoration: new BoxDecoration(
                      border: new Border.all(color: Colors.blueAccent),
                      borderRadius: BorderRadius.horizontal( left:Radius.circular(30.0) ,right:Radius.circular(30.0) ),
                      ),
                    padding: EdgeInsets.only(bottom: 10.0),
                    child:Column(
                      children:<Widget>[
                        Row(children: <Widget>[
                          Container(
                              padding:  EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 30.0),
                              alignment: Alignment.topRight,
                              child:IconButton(
                                onPressed:(){ hi(element.dat)?null:change(element);},
                                icon:Icon(Icons.star),color:element.color ,)),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                Container(
                                  alignment: Alignment.topCenter,
                                  padding: const EdgeInsets.only(bottom: 1.0),
                                  child: Text(
                                    element.name,
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 40.0),),),
                                Container(
                                  margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 90.0),
                                  child:Text(element.dis,style: TextStyle(color: Colors.grey[800],fontSize: 18.0),),),],), ),
                          Container(
                            padding:  EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 80.0),
                            alignment: Alignment.topLeft,
                            child:IconButton(
                                onPressed:null,
                                icon:Icon(Icons.done_all,color: hi(element.dat)?Colors.grey:Colors.lightBlue,)),),],),],))],);
          }).toList()));}}

【讨论】:

  • 我已经考虑过这个解决方案。但是,考虑拥有大量图标是一件可怕的事情。有什么解决这个问题的建议吗?
  • 按照相同的概念它不起作用;你能检查我的编辑吗?
  • 在此您只需传递颜色,因此它会更改颜色但不会更改对象。
  • 是的!这行得通,非常感谢,非常感谢。但是我想知道为什么它首先不起作用,尽管我们更改了作为对象一部分的属性中的颜色;我只是想了解这个概念
猜你喜欢
  • 2012-03-15
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 2012-03-30
  • 2021-05-25
  • 1970-01-01
相关资源
最近更新 更多