我有一个自定义文本类和一个自定义文本样式。
当我更改自定义texstyle颜色,但颜色未更改时。我想要红色的结果aaaaa和黑色的bbbbb。
代码已附加
提前感谢
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
MyCustomText(text: "aaaaa", style: CtrBlblStyle()),
MyCustomText(
text: "bbbbb", style: CtrBlblStyle(color: Colors.black)),
],
),
),
);
}
}
class CtrPublic {
static const Color textColor = Colors.red;
}
class CtrBlblStyle extends TextStyle {
final Color color;
CtrBlblStyle({
this.color = CtrPublic.textColor,
});
}
class MyCustomText extends StatelessWidget {
final String text;
final TextStyle style;
MyCustomText({
this.text,
this.style,
});
@override
Widget build(BuildContext context) {
return Text(
text,
style: CtrBlblStyle(),
);
}
}发布于 2021-01-11 01:45:39
更新MyCustomText以避免创建新的CtrlBlblStyle实例。
您正在将使用不同TextStyles值创建的不同CtrlBlblStyle实例传递给MyCustomText,而不是在类中使用它们,而是创建一个新的CtrlBlblStyle实例,该实例默认为红色,因为它没有接收任何构造函数参数,请更改下面这一行:
style: CtrBlblStyle(),为此:
style: style,类:
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
MyCustomText(text: "aaaaa", style: CtrBlblStyle()),
MyCustomText(
text: "bbbbb", style: CtrBlblStyle(color: Colors.black)),
],
),
),
);
}
}
class CtrPublic {
static const Color textColor = Colors.red;
}
class CtrBlblStyle extends TextStyle {
final Color color;
CtrBlblStyle({
this.color = CtrPublic.textColor,
});
}
class MyCustomText extends StatelessWidget {
final String text;
final TextStyle style;
MyCustomText({
this.text,
this.style,
});
@override
Widget build(BuildContext context) {
return Text(
text,
// Update this line
style: style,
);
}
}发布于 2021-01-11 01:24:19
你可以这样做。没有必要走这么远的路。
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
MyCustomText(text: "aaaaa"),
MyCustomText(
text: "bbbbb", style:TextStyle(color:Colors.black)),
],
),
),
);
}
}
class MyCustomText extends StatelessWidget {
final String text;
final TextStyle style;
MyCustomText({
this.text,
this.style
});
@override
Widget build(BuildContext context) {
return Text(
text,
style: style??TextStyle(color:Colors.red),
);
}
}https://stackoverflow.com/questions/65656036
复制相似问题