简体   繁体   English

Flutter - setState() 没有更新按钮的文本颜色?

[英]Flutter - setState() isn't updating the button's text color?

The problem is, whenever I click on the Like button, the color isn't changing for the button icon and the text as I am updating on onPressed() method.问题是,每当我单击“赞”按钮时,按钮图标和文本的颜色都没有改变,因为我正在更新 onPressed() 方法。 What could be the issue, please guide?可能是什么问题,请指导? I am experimenting with flutter from the last 1 month.我正在试验过去 1 个月的颤振。

This is my class code:这是我的课程代码:

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];
              }),
        ));
  }
}

This is the output screenshot:这是输出截图:

在此处输入图像描述

Thank you.谢谢你。

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
You can create only one widget and bind those data into this widget您只能创建一个小部件并将这些数据绑定到该小部件中

code snippet代码片段

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

working demo工作演示

在此处输入图像描述

full code完整代码

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);
          }),
    ));
  }
}

The setState() method notifies the framework that the internal state of the Stateful widget has changed. setState() 方法通知框架有状态小部件的内部状态已更改。 Calling this method is what triggers the widget to rebuild with the latest state values, So put all your code in build method and it will work调用此方法会触发小部件使用最新的状态值进行重建,因此将所有代码放入构建方法中,它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM