簡體   English   中英

Flutter中如何動態改變文字顏色?

[英]How to change the color of text dynamically in Flutter?

這是我的應用程序的一小部分里程碑

我通過對每個細節進行硬編碼來做到這一點。 但我想動態地實現這一點。

問題是 - 如果我編碼一段時間,我將輸入我編碼的小時數,如果我達到我的里程碑,里程碑文本必須變為紅色,下一個里程碑必須變為綠色。

到目前為止,這是我的代碼

我的里程碑清單

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參數。 我無法超越這一點。

編輯:如果你想為每件商品使用不同的顏色,你可以像這樣使用 function,

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"),
),

如果我明白你清楚
如果條件在 map 中,您可以執行此操作
代碼片段

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

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM