为什么setState不更新按钮文本颜色?

时间:2019-11-28 06:33:14

标签: android ios flutter state

问题是,每当我单击“赞”按钮时,在我通过onPressed()方法更新时,按钮图标和文本的颜色都不会改变。可能是什么问题,请指导?我正在尝试最近1个月的抖动。

这是我的课程代码:

class SingelBattleAllComments extends StatefulWidget {
  final int battleId; // add info

  SingelBattleAllComments({@required this.battleId});

  @override
  _SingelBattleAllCommentsState createState() =>
      _SingelBattleAllCommentsState(battleId: battleId);
}

class _SingelBattleAllCommentsState extends State<SingelBattleAllComments> {
  final int battleId; // add info

  final List<String> profileImages = [
    'https://www.codecyan.com/images/omi-shah-codecyan-founder-ceo.jpg'];

  Color likeButtonColor;
  List<Widget> commentsListItems;

  _SingelBattleAllCommentsState({@required this.battleId});

  @override
  void initState() {
    likeButtonColor = new Color(0xff333030);

    commentsListItems = List<Widget>.generate(5, (i) {
      return Column(
        children: <Widget>[
          SizedBox(height: 15),
          Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  color: Colors.white,
                  border: Border.all(color: Colors.black12, width: 1)),
              child: Padding(
                  padding: EdgeInsets.all(7),
                  child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        ClipRRect(
                            borderRadius: BorderRadius.circular(50.0),
                            child: CachedNetworkImage(
                                fit: BoxFit.cover,
                                imageUrl: profileImages[0

                                    ],
                                width: 50,
                                height: 50)),
                        SizedBox(width: 10),
                        Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("OMi Shah",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                  )),
                              SizedBox(height: 3),
                              Container(
                                width: 250, //screenWidth * 0.65,
                                child: Text(
                                  "Hello",
                                ),
                              ),
                              SizedBox(height: 5),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  FlatButton.icon(
                                    onPressed: () {
                                      setState(() {
                                        likeButtonColor = Colors.red;
                                      });
                                    },
                                    label: Text("Like (291)",
                                        style:
                                            TextStyle(color: likeButtonColor)),
                                    icon: Icon(Icons.thumb_up,
                                        color: likeButtonColor),
                                  ),
                                  SizedBox(width: 15),
                                  FlatButton.icon(
                                    onPressed: () {},
                                    label: Text("Report",
                                        style: TextStyle(
                                            color: const Color(0xff333030))),
                                    icon: Icon(Icons.report,
                                        color: const Color(0xff333030)),
                                  ),
                                ],
                              )
                            ])
                      ])))
        ],
      );
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
          child: ListView.builder(
              padding:
                  EdgeInsets.only(left: 20, top: 10, right: 20, bottom: 10),
              itemCount: commentsListItems.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return commentsListItems[index];
              }),
        ));
  }
}

这是输出屏幕截图:

enter image description here

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以在下面复制粘贴运行完整代码
您只能创建一个小部件并将这些数据绑定到该小部件

代码段

 commentsListItems = List<int>.generate(5, (i) => i + 1);
 ...
 Widget Comment(int index) {
    return Column(
      children: <Widget>[
        SizedBox(height: 15),

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: SingelBattleAllComments(battleId: 1,),
    );
  }
}

class SingelBattleAllComments extends StatefulWidget {
  final int battleId; // add info

  SingelBattleAllComments({@required this.battleId});

  @override
  _SingelBattleAllCommentsState createState() =>
      _SingelBattleAllCommentsState(battleId: battleId);
}

class _SingelBattleAllCommentsState extends State<SingelBattleAllComments> {
  final int battleId; // add info

  final List<String> profileImages = [
    'https://www.codecyan.com/images/omi-shah-codecyan-founder-ceo.jpg'
  ];

  Color likeButtonColor;
  List<int> commentsListItems;

  _SingelBattleAllCommentsState({@required this.battleId});

  @override
  void initState() {
    likeButtonColor = Color(0xff333030);
    commentsListItems = List<int>.generate(5, (i) => i + 1);
    super.initState();
  }

  Widget Comment(int index) {
    return Column(
      children: <Widget>[
        SizedBox(height: 15),
        Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                color: Colors.white,
                border: Border.all(color: Colors.black12, width: 1)),
            child: Padding(
                padding: EdgeInsets.all(7),
                child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: CachedNetworkImage(
                            fit: BoxFit.cover,
                            imageUrl: profileImages[0

                            ],
                            width: 50,
                            height: 50),
                      ),
                      SizedBox(width: 10),
                      Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text("OMi Shah",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                )),
                            SizedBox(height: 3),
                            Container(
                              width: 250, //screenWidth * 0.65,
                              child: Text(
                                "Hello",
                              ),
                            ),
                            SizedBox(height: 5),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                FlatButton.icon(
                                  onPressed: () {
                                    setState(() {
                                      likeButtonColor = Colors.red;
                                    });
                                  },
                                  label: Text("Like (291)",
                                      style: TextStyle(color: likeButtonColor)),
                                  icon: Icon(Icons.thumb_up,
                                      color: likeButtonColor),
                                ),
                                SizedBox(width: 15),
                                FlatButton.icon(
                                  onPressed: () {},
                                  label: Text("Report",
                                      style: TextStyle(
                                          color: const Color(0xff333030))),
                                  icon: Icon(Icons.report,
                                      color: const Color(0xff333030)),
                                ),
                              ],
                            )
                          ])
                    ])))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      child: ListView.builder(
          padding: EdgeInsets.only(left: 20, top: 10, right: 20, bottom: 10),
          itemCount: commentsListItems.length,
          itemBuilder: (BuildContext ctxt, int index) {
            return Comment(index);
          }),
    ));
  }
}

答案 1 :(得分:0)

setState()方法通知框架有状态窗口小部件的内部状态已更改。调用此方法是触发窗口小部件以最新状态值进行重建的原因,因此将您的所有代码放入build方法中,它将起作用