如何在 Flutter 中为不同语言环境设置不同字体

Sam*_*eer 7 dart flutter

有什么办法可以为不同的字体设置不同的字体locals吗?英文字体是我的应用程序的默认字体,但我的阿拉伯语需要不同的字体locale

小智 8

使用区域设置和主题

这个问题需要两件事:

  • 获取系统区域设置
  • Theme根据区域设置提供正确的值。

window.locale通过调用from可以轻松检索区域设置dart:ui。如果您需要有关区域设置方面的更多信息,这里有一篇关于区域设置的非常深入的堆栈溢出帖子。

根据区域设置,我们将 的fontFamily属性设置ThemeData为 pubspec.yaml 文件中定义的所需字体。(有关添加自定义字体的说明在这里

例子

import 'dart:ui';
import 'package:flutter/material.dart';

class App extends StatefulWidget {
  const App({Key? key}) : super(key: key);

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> {
  VoidCallback rebuildOnLocaleChange() => () => setState(() {});

  @override
  Widget build(BuildContext context) {
    // Retrieve locale from the system information.
    Locale myLocale = window.locale;
    PlatformDispatcher.instance.onLocaleChanged = rebuildOnLocaleChange();

    return MaterialApp(
      theme: ThemeData(
        // If language is english - we use the default font which is a sans-serif roboto font
        // If not, we use the serif roboto font, must be added in asset and pubspec.yaml to work.
        // TODO: replace the languageCode check with what you need.
        fontFamily: myLocale.languageCode == "en" ? null : "RobotoSerif",
      ),
      home: const AppScreen(),
    );
  }
}

// Just a simple screen with a text updating when the locale changes.
class AppScreen extends StatelessWidget {
  const AppScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          "Test",
          style: Theme.of(context).textTheme.headline1,
        ),
      ),
    );
  }
}

main() => runApp(const App());
Run Code Online (Sandbox Code Playgroud)

下图显示了当 languageCode 为“en”(左)时主题设置为默认字体,以及其他区域设置的自定义字体(右)。

默认字体 自定义字体