Flutter 颤振:向文本小部件添加一个简单的包装器
我来自一个反应的世界,试图让我的头左右扑动和飞镖 我经常使用具有相同参数的文本小部件,因此考虑一种重用代码的方法似乎是合理的。我创建了一个使用它的包装器:Flutter 颤振:向文本小部件添加一个简单的包装器,flutter,dart,Flutter,Dart,我来自一个反应的世界,试图让我的头左右扑动和飞镖 我经常使用具有相同参数的文本小部件,因此考虑一种重用代码的方法似乎是合理的。我创建了一个使用它的包装器: import 'package:flutter/material.dart'; TextStyle getThemeProperty(type, TextTheme textTheme) { switch (type) { case 'headline1': return textTheme.headline1;
import 'package:flutter/material.dart';
TextStyle getThemeProperty(type, TextTheme textTheme) {
switch (type) {
case 'headline1':
return textTheme.headline1;
case 'headline2':
return textTheme.headline2;
case 'headline3':
return textTheme.headline3;
default:
return textTheme.bodyText2;
}
}
class CustomText extends StatelessWidget {
const CustomText({Key key, this.type, this.text, this.color}) : super(key: key);
final type;
final text;
final color;
@override
Widget build(BuildContext context) {
var textTheme = Theme.of(context).textTheme;
var style = getThemeProperty(type, textTheme);
if (this.color != null) style.color = this.color;
return Text(
this.text,
style: style,
);
}
}
// Usage
CustomText(
text: 'Some Heading',
type: 'headline2',
color: Colors.black
)
如果颜色属性作为参数传递,则可以设置颜色,但Dart的编译器不喜欢它。它向我抛出错误:“颜色”不能用作setter,因为它是最终的。
试着找一个不同的设定者,或者让“颜色”成为非最终颜色
我计划对
fontWeight
和textAlign
属性也做同样的操作。我的意思是,我怎样才能做到这一点,根据需要向样式对象添加新的道具?dart编译器不满意的原因只是因为TextStyle
的color
属性被声明为final。因此,要使用新颜色,必须创建TextStyle
的新实例
幸运的是,TextStyle类附带了一个copyWith方法,该方法返回TextStyle的编辑副本
final type;
final text;
final color;
@override
Widget build(BuildContext context) {
var textTheme = Theme.of(context).textTheme;
var style = getThemeProperty(type, textTheme);
return Text(
this.text,
// Added this...
style: style.copyWith(color: color ?? style.color),
);
}
作为旁注,在制作可重用的小部件时,键入参数总是一个好主意。这是因为可以使用任何类型的变量。因此,您可以传递一个int
// DON'T DO THIS
final type;
final text;
final color;
// DO THIS
final String type;
final String text;
final Color color;
另外,添加this
关键字以引用类中的变量而不使用变量阴影也是不必要的
// DON'T
this.text
// DO
text