我正在尝试将颜色/主题信息传递给不同的小部件。我的应用程序包含一个新闻页面,然后打开单个文章。这些文章应该有不同的颜色,具体取决于打开它们的几个新闻页面中的哪个,所以我想从我的文章小部件外部引导主题/颜色信息。
我做了一个类来保存一些颜色/主题信息,如下所示:
class NewsTheme0 {
static Color headerColor = Color.fromRGBO(30, 60, 90, 1);
static TextStyle headerFontStyle() {
return TextStyle(
color:Color.fromRGBO(200,100,0,1),
fontSize:28.5,
letterSpacing: -1.4,
fontWeight: FontWeight.w700
);
}
}
class NewsTheme1 {
static Color headerColor = Color.fromRGBO(0, 0, 0, 1);
static TextStyle headerFontStyle() {
return TextStyle(
color:Color.fromRGBO(255, 255, 255, 1),
fontSize:15,
fontWeight: FontWeight.w700
);
}
}
然后我的内News
页,我appBar
,我成功地获取该颜色信息:
Scaffold(
appBar: AppBar(
centerTitle: false,
backgroundColor: NewsTheme0.headerColor,
title: Text('News',
style: NewsTheme0.headerFontStyle()),
elevation: 0,
) ...
从我的News
主页打开一个Article
页面,当我打开文章小部件时,我传递了颜色信息
Navigator.push(
context,
MaterialPageRoute(builder: (context) => OpenAnArticle(articleid: 231, theme: NewsTheme0)));
我的文章里面是这样的:
class OpenAnArticle extends StatefulWidget {
OpenAnArticle({ Key? key, required this.articleid, required this.theme}) : super(key: key);
final int articleid;
final theme;
@override
_OpenAnArticle createState() => _OpenAnArticle();
}
但是当我尝试在我的article
. 我需要传递主题信息,因为我不会提前知道它们将从我的各种颜色主题页面中的哪一个到达。
Scaffold(
appBar: AppBar(
centerTitle: false,
backgroundColor: widget.theme.headerColor,
title: Text('Article',
style: widget.theme.headerFontStyle()),
elevation: 0,
) ...
那是因为当您这样做时NewsTheme0
,您正在访问一个类型的对象,Type
并且您不能仅使用其类型来访问类的(静态)方法。您可以使用“枚举”,如下所示:
// Declaring the abstract class which each theme will inherit from
abstract class NewsTheme {
static const NewsTheme theme0 = _NewsTheme0();
static const NewsTheme theme1 = _NewsTheme1();
const NewsTheme();
Color get headerColor;
TextStyle headerFontStyle();
}
class _NewsTheme0 extends NewsTheme {
const _NewsTheme0() : super();
@override
Color get headerColor => Color.fromRGBO(30, 60, 90, 1);
@override
TextStyle headerFontStyle() {
return TextStyle(
color:Color.fromRGBO(200,100,0,1),
fontSize:28.5,
letterSpacing: -1.4,
fontWeight: FontWeight.w700
);
}
}
class _NewsTheme1 extends NewsTheme {
const _NewsTheme1() : super();
@override
Color get headerColor => Color.fromRGBO(0, 0, 0, 1);
@override
TextStyle headerFontStyle() {
return TextStyle(
color:Color.fromRGBO(255, 255, 255, 1),
fontSize:15,
fontWeight: FontWeight.w700
);
}
}
在您的小部件代码中:
class OpenAnArticle extends StatefulWidget {
final int articleid;
// Expect a NewsTheme object
final NewsTheme theme;
const OpenAnArticle({ Key? key, required this.articleid, required this.theme}) : super(key: key);
@override
_OpenAnArticle createState() => _OpenAnArticle();
}
然后,如果您想将主题传递给其构造函数,您只需访问以下静态字段NewsTheme
:
Navigator.push(
context,
MaterialPageRoute(builder: (_) => OpenAnArticle(articleid: 231, theme: NewsTheme.theme0)),
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句