每次我需要访问我当前主题的 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
            )
        )
    );
}

推荐答案

你可以在BuildContext上创建分机,比如,

extension MyThemeExtension on BuildContext {
  ColorScheme get colorSchema => Theme.of(this).colorScheme;
}

然后使用Like context.colorSchema;,但实际上我更喜欢编写整行代码,比如

@override
Widget build(BuildContext context) {
  final theme = Theme.of(context);
  final colorSchema = theme.colorSchema;
  final textTheme = theme.textTheme;

  return Scaffold(...);
}

Flutter相关问答推荐

如何让GridView.builder用另外两个小部件来占据屏幕的剩余部分

从Flutter应用程序解释蓝牙BLE数据:了解Sylvania压力值

如何使一个悬浮的appbar在flutter?

想更新ListView上的索引点击块Flutter

在VSCode中运行应用程序而不进行调试时,控制台仍显示为调试模式

处理 flutter/dart 模型中的空值

flutter Listview构建器溢出

使用 Play Integrity API 时,Firebase 电话身份验证问题缺少客户端标识符错误

Flutter 动保存新的变量值

无法使用 bloc 更新 ListView.builder 的特定时间

是否有可能减少代码的编写,例如:ref.read(countProvider.notifier) - 在构建方法中?

具有 BLOC 和存储库模式的 Flutter Workmanager

如何在向下滚动时隐藏顶部卡片并在向上滚动时出现?

通过点击缩略图加载全屏图像

在 CircleAvatar 中放置芯片

如何在 Flutter 中使用简写 IF 禁用单选按钮?

Flutter 本地通知在最新版本中不起作用

更新未知文档 ID firebase\flutter 中的字段

如何在 Flutter 中的页面加载上的 Listview 上应用自动滚动

如何在没有上下文的情况下使用国际Flutter ?