我有 2 段文本,它们来自 API 调用,一个是德语,一个是英语,它们作为参数输入到基本模板中,该模板包含文本的自定义样式。第二个文本,翻译与背景颜色相同,当按下显示按钮时,我希望颜色变为白色(可见)。为清晰起见的图像:
我将如何更改第二个文本的颜色,由于通过自定义模板提供数据(请参阅下面的代码),我不确定。 任何方向正确的观点都值得赞赏。
主类
class MistakesScreen extends StatefulWidget {
String username;
MistakesScreen({this.username});
@override
_MistakesScreenState createState() => _MistakesScreenState();
}
class _MistakesScreenState extends State<MistakesScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Hello ${widget.username}"),
),
body: Container(
child: FutureBuilder(
future: fetchGermanPhrases(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Connection State None');
case ConnectionState.active:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
var gname = snapshot.data['gname'].toString();
var ename = snapshot.data['ename'].toString();
return BasicExerciseTemplate(textOne: gname, textTwo: ename);
default:
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
}
模板和按钮代码:
class BasicTextTemplate extends StatelessWidget {
final String text;
final Color colour;
BasicTextTemplate({this.text, this.colour});
@override
Widget build(BuildContext context) {
return Center(
child: Container(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(
text,
style: TextStyle(
color: colour,
fontSize: 30,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic,
),
),
),
width: 350,
decoration: BoxDecoration(
color: Colors.green.shade800,
borderRadius: BorderRadius.circular(8),
),
),
);
}
}
class BasicExerciseTemplate extends StatelessWidget {
final String textOne;
final String textTwo;
BasicExerciseTemplate({this.textOne, this.textTwo});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: BasicTextTemplate(text: textOne, colour: Colors.white),
),
Padding(
padding: const EdgeInsets.all(8.0),
child:
BasicTextTemplate(text: textTwo, colour: Colors.green.shade800),
),
RevealButton()
],
),
);
}
}
class RevealButton extends StatelessWidget {
final String textOne;
final String textTwo;
RevealButton({this.textOne, this.textTwo});
@override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
child: Text('Reveal'),
color: Colors.blueAccent,
textColor: Colors.white,
onPressed: () {
print('Reveal Pressed');
},
),
);
}
}
答案 0 :(得分:2)
试试这个
isReveal = false;
onPressed: () {
setState(() {
IsReveal = true
});
},
BasicTextTemplate(text: textTwo, colour:!isReveal ? Colors.green.shade800:Colors.white);
答案 1 :(得分:1)
要实现您的目标,我建议您使用 Visibility
小部件。它控制给定的孩子是否可见。我认为这会容易得多。
例如:
Visibility(
visible: myBoolean,
child: Text(
"Die Deutschen sind sehr nett",
style: TextStyle(fontSize: 20),
),
),
只需使用一个函数,您可以在其中更改布尔值并触发 setState
方法。这样你就可以根据条件隐藏或显示你的文本。有关详细信息,请参阅:
https://api.flutter.dev/flutter/widgets/Visibility-class.html