【问题标题】:How to change the color of text dynamically in Flutter?如何在 Flutter 中动态改变文本的颜色?
【发布时间】:2020-02-02 12:53:26
【问题描述】:

这是我的应用程序的一小部分

我通过对每个细节进行硬编码来实现这一点。但我想动态地实现这一点。

问题是 - 如果我编码一段时间,我将输入我编码的小时数,如果我达到我的里程碑,里程碑文本必须变为红色,下一个里程碑必须变为绿色。

这是我目前的代码

我的里程碑列表

List milestoneList = [10, 25, 50, 100, 250, 500, 750, 1000];

将列表映射到小部件

Row(
     mainAxisAlignment: MainAxisAlignment.center,
     children: milestoneList.map((item) {
       return Padding(
       padding: const EdgeInsets.all(8.0),
       child: Text(
       item.toString(),
       style: TextStyle(
       fontWeight: FontWeight.bold,),
    ),
   );
 }).toList(),

到目前为止,我能够破解我需要将值传递给TextStylecolor 参数。我无法超越这一点。

【问题讨论】:

    标签: android flutter flutter-layout


    【解决方案1】:

    编辑:如果你想为每个项目提供不同的颜色,你可以使用这样的功能,

    Color getColor(number) {
       if (number > 0 && number < 100) return Colors.red;
       if (number >= 100 && number < 200) return Colors.blue;
       ...
    }
    

    并更新颜色属性,

    color: getColor(item),
    

    在里程碑列表下面添加这个

    Color textColor = Colors.black; // Default color
    

    像这样改变你的文本样式,

    TextStyle(
      fontWeight: FontWeight.bold,
      color: textColor,
    ),
    

    这样做是为了更新颜色,

    FlatButton(
      onPressed: () {
        setState(() => textColor =
            Color((Random().nextDouble() * 0xFFFFFF).toInt() << 0)
                .withOpacity(1.0)); // this is generate random color, u can use your own..
      },
      child: Text("change color"),
    ),
    

    【讨论】:

    • 这是我根据你的方法编写的代码 Color getColor(double item) { if (item &lt; milestoneCount) { return Colors.red; } else if (item &gt; milestoneCount &amp;&amp; item == item++) { return Colors.teal; } return Colors.black; } 事情是我得到了 - 红色表示已完成的里程碑,其余部分为蓝绿色。但我只想要蓝绿色作为我的下一个里程碑。
    • 我不明白,如果你能分享你想要的颜色的油漆文件,我可以很快帮你。
    • 什么是画图文件?
    • 我的意思是,如果你画你想要的东西,我可以帮助你。或者告诉我更多细节,比如:0-100 红色,等于 100 蓝色,>100 黄色......
    【解决方案2】:

    如果我明白你清楚
    您可以在地图中使用 if 条件
    代码 sn -p

    milestoneList.map((item) {
                          if (item > 100) {
    

    完整代码

    import 'package:flutter/material.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: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      // This widget is the home page of your application. It is stateful, meaning
      // that it has a State object (defined below) that contains fields that affect
      // how it looks.
    
      // This class is the configuration for the state. It holds the values (in this
      // case the title) provided by the parent (in this case the App widget) and
      // used by the build method of the State. Fields in a Widget subclass are
      // always marked "final".
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      List milestoneList = [];
      void _incrementCounter() {
        setState(() {
          // This call to setState tells the Flutter framework that something has
          // changed in this State, which causes it to rerun the build method below
          // so that the display can reflect the updated values. If we changed
          // _counter without calling setState(), then the build method would not be
          // called again, and so nothing would appear to happen.
          _counter++;
        });
      }
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        milestoneList = [10, 25, 50, 100, 250, 500, 750, 1000];
      }
    
      @override
      Widget build(BuildContext context) {
        // This method is rerun every time setState is called, for instance as done
        // by the _incrementCounter method above.
        //
        // The Flutter framework has been optimized to make rerunning build methods
        // fast, so that you can just rebuild anything that needs updating rather
        // than having to individually change instances of widgets.
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
          ),
          body: Center(
            // Center is a layout widget. It takes a single child and positions it
            // in the middle of the parent.
            child: Column(
              // Column is also a layout widget. It takes a list of children and
              // arranges them vertically. By default, it sizes itself to fit its
              // children horizontally, and tries to be as tall as its parent.
              //
              // Invoke "debug painting" (press "p" in the console, choose the
              // "Toggle Debug Paint" action from the Flutter Inspector in Android
              // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
              // to see the wireframe for each widget.
              //
              // Column has various properties to control how it sizes itself and
              // how it positions its children. Here we use mainAxisAlignment to
              // center the children vertically; the main axis here is the vertical
              // axis because Columns are vertical (the cross axis would be
              // horizontal).
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: milestoneList.map((item) {
                      if (item > 100) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            item.toString(),
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        );
                      }
                      if (item < 100) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            item.toString(),
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.red,
                            ),
                          ),
                        );
                      }
                      if (item == 100) {
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(
                            item.toString(),
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.green,
                            ),
                          ),
                        );
                      }
                    }).toList()),
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.display1,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    }
    

    【讨论】:

    • 感谢您的回复。我本可以使用您的方法,但问题是我想动态计算小时数并显示颜色。
    猜你喜欢
    • 2019-09-30
    • 2019-09-10
    • 2022-11-18
    • 1970-01-01
    • 2021-12-04
    • 2019-01-27
    • 1970-01-01
    • 2014-06-20
    • 2012-05-26
    相关资源
    最近更新 更多