[英]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.