繁体   English   中英

如何在 Flutter 到 dart 中更改 Widget 的值

[英]How to change the Value of a Widget in Flutter through dart

我想知道如果满足特定条件,我可以更改 flutter 中子小部件的值,例如尾随图标的颜色

这是一些伪代码:

if(condition){
   trailing Icon(Icons.favorite).color = Colors.red[500]
}else{
  trailing = Icon(Icons.Favorite).color = Colors.blue[300]
}

谢谢你。

你想要这样的东西吗?

在此处输入图像描述

如果是,请尝试以下代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool colorIndex = true;
  void _changeColor(val) {
    setState(() {
      this.colorIndex = val;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            _changeColor(!colorIndex);
          },
          child: Icon(Icons.touch_app),
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(50.0),
            child: Card(
              child: ListTile(
                title: Text('Click FAB to change color'),
                trailing: Icon(
                  Icons.favorite,
                  color: colorIndex ? Colors.red[500] : Colors.blue[300],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

您可以在您定义的任何条件下更改任何内容。 最简单的示例是使用setState更新可以在build期间检查的值。 这个值可以在你喜欢的任何条件下改变。 调用setState将触发 UI 重建(调用build方法)

这是一个小部件。 它显示文本“Hello, World”。 在屏幕中央。 顶部的 AppBar 有一个领先的 IconButton Widget,当 IconButton 被按下时,它将切换“Hello. World!”的颜色。 文本。 它通过更新 Widget 的 state 并切换blue变量的值来实现这一点。 条件是: if (blue) {}或“如果蓝色等于true则改变颜色”。 在 UI 的build过程中,代码检查blue的值并确定将什么TextStyle应用于“Hello, World”。 文本。

import 'package:flutter/material.dart';

class ColorChangeWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ColorChangeWidgetState();
}

class _ColorChangeWidgetState extends State<ColorChangeWidget> {
  
  bool blue = false;

  @override
  Widget build(BuildContext context) {
    TextStyle style = TextStyle(color: Colors.black);
    if (blue) {
      style = TextStyle(color: Colors.blue);
    }
    return Scaffold(
      appBar: AppBar(
        title: Text("Test"),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.add),
          onPressed: () {
            setState(() {
              blue = !blue;
            });
          },
        ),
      ),
      body: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(8.0),
        child: Text("Hello, World!", style: style)
      )
    ); 
  }
  
}

暂无
暂无

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

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