【问题标题】:Flutter - setState() isn't updating the button's text color?Flutter - setState() 没有更新按钮的文本颜色?
【发布时间】:2019-11-28 06:33:14
【问题描述】:

问题是,每当我点击 Like 按钮时,按钮图标和文本的颜色都不会改变,因为我正在更新 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];
              }),
        ));
  }
}

这是输出截图:

谢谢。

【问题讨论】:

  • 你为什么要把所有的代码都放在 initState 中?
  • 我已经放入 initState() 来填充一些演示数据?我做错了吗?
  • 实际上setState 有效(尝试在setState 中添加commentsListItems.removeLast();),这将有效。我认为当您使用 List.generate 并返回 Column 时,不再引用 likeButtonColor。所以:这不是关于 setState,而是关于你的列表 使用情况
  • @IbrahimKarahan 实际上,你是对的。但是,我不知道为什么颜色没有更新:(

标签: android ios flutter state


【解决方案1】:

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

代码sn-p

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

工作演示

完整代码

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 2019-12-16
      • 1970-01-01
      • 2022-01-07
      • 2019-05-27
      • 1970-01-01
      • 2017-04-10
      • 2011-03-14
      相关资源
      最近更新 更多