首页 > 解决方案 > Flutter Applying font family from Theme in Main.dart 文件被应用。但是从自定义文件应用时相同,仅在应用栏上应用

问题描述

我正在从外部主题文件中应用 Flutter 应用程序中的主题

字体详细信息已添加到 pubspec.yaml 文件中。

在方案 1 中,从自定义文件应用主题。问题是字体仅应用于 AppBar。不在应用程序的任何其他部分。

在场景二中,主题直接应用在 main.dart 文件中。该字体应用于所有小部件。没有其他变化。

有人可以帮忙吗。

方案 1

void main() {

  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''), 
        const Locale('fr', ''), 
      ],
      title: 'Hello App',
      theme: CustomTheme.theme,
      // home: Login(),
      routes: {
        '/' : (ctx) => LoginScreen(),
      },
    );

  }
}

自定义主题文件

class CustomTheme {
  static ThemeData get theme {
    return ThemeData(
      fontFamily: "Montserrat",
      primarySwatch: CustomColors.primarySwatch,
      accentColor: CustomColors.accentColor,
      iconTheme: IconThemeData(
          color: Colors.white
      ),
      textTheme: ThemeData
          .light()
          .textTheme
          .copyWith(
          headline6: TextStyle(color: CustomColors.textPrimary)
      ),
    );
  }
}

方案 1

方案 2

void main() {

  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''), // English, no country code
        const Locale('fr', ''), // Spanish, no country code
      ],
      title: 'Hello App',
      theme: ThemeData(
        fontFamily: "Montserrat"
      ),
      // home: Login(),
      routes: {
        '/' : (ctx) => LoginScreen(),
      },
    );

  }
}

方案 2

标签: flutterflutter-themeflutter-font

解决方案


推荐阅读