【问题标题】:How do I temporarily change a text color (and back) in a Flutter widget?如何临时更改 Flutter 小部件中的文本颜色(并返回)?
【发布时间】:2019-08-26 00:53:50
【问题描述】:

我正在寻找一种解决方案,将文本小部件中的文本颜色临时更改为红色 3 秒。我目前可以将其设置为红色,但如何将其更改为在此持续时间之后的状态?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    像这样……

    import 'dart:async';
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: SO(),
        );
      }
    }
    class SO extends StatefulWidget {
      @override
      _SOState createState() => _SOState();
    }
    
    class _SOState extends State<SO> {
      static final orgColor = Colors.black;
      var currentColor  = orgColor;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Center(child: Text("this is colored",style: TextStyle(color: currentColor,fontSize: 40),)),
          floatingActionButton: FloatingActionButton(onPressed: () {
            setState(() {
              currentColor = Colors.red;
            });
            Timer(Duration(seconds: 3),(){
              setState(() {
                currentColor = orgColor;
              });
            });
          },),
        );
      }
    }
    import 'dart:async';
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: SO(),
        );
      }
    }
    class SO extends StatefulWidget {
      @override
      _SOState createState() => _SOState();
    }
    
    class _SOState extends State<SO> {
      static final orgColor = Colors.red;
      var currentColor  = orgColor;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Center(child: Text("this is colored",style: TextStyle(color: currentColor,fontSize: 40),)),
          floatingActionButton: FloatingActionButton(onPressed: () {
            setState(() {
              currentColor = Colors.blue;
            });
            Timer(Duration(seconds: 2),(){
              setState(() {
                currentColor = orgColor;
              });
            });
          },),
        );
      }
    }
    

    基本上是设置一个定时器等待一段时间(这里是2秒)然后重置状态。

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 2013-04-20
      • 2021-07-07
      • 2021-05-15
      • 2020-12-04
      • 2021-11-22
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多