每次我需要访问我当前主题的 colored颜色 时,我必须写Theme.of(context).colorScheme.{come color}
.
这意味着我必须在我需要使用 colored颜色 的几乎每一行中写下这一点,这是一个巨大的麻烦.
如果我在每个类中都设置一个变量‘我需要Colors build()
方法,比如:final colorScheme = Theme.of(context).colorScheme
,可能会更短.
但这仍然意味着我必须在每节课上写下这一点.
有没有一种方法可以创建一个缩写,我可以从一个文件中导入并在所有类的整个文件中使用,而不需要反复编写相同的东西?
ANSWER:
我发现这个GitHub回购对每个人来说都是完美的解决方案,@md也是这样说的.亚辛·谢赫的回答. The GitHub repo file with the solution and more convenient shortcuts for most used lines of code:个
import 'package:flutter/material.dart';
extension BuildContextExtensions on BuildContext {
ThemeData get _theme => Theme.of(this);
TextTheme get textTheme => _theme.textTheme;
ColorScheme get colorScheme => _theme.colorScheme;
Size get deviceSize => MediaQuery.sizeOf(this);
}
Then, to access the current color scheme:导入具有此定义扩展名的文件,where you want to access the theme, use: context.colorScheme
.
使用示例:
@override
Widget build(BuildContext context) {
return Container(
color: context.colorScheme.primaryContainer,
child: Text(
'Example container',
style: TextStyle(
color: context.colorScheme.onPrimaryContainer
)
)
);
}