首页 > 解决方案 > Flutter中如何通过dart改变一个Widget的Value

问题描述

我想知道如果满足某个条件,我可以在颤动中更改子小部件的值,例如尾随图标的颜色

这是一些伪代码:

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

谢谢你。

标签: flutterdart

解决方案


你想要这样的东西吗?

在此处输入图像描述

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

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


推荐阅读