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());
3条答案
按热度按时间ijnw1ujt1#
使用Locale和Theme
这个问题需要两件事:
Theme
。通过从
dart:ui
调用window.locale
可以很容易地检索到locale。如果您需要有关locale方面的更多信息,可以使用quite in-depth stack overflow post on locale here。根据区域设置,我们将
ThemeData
上的fontFamily
属性设置为pubspec.yaml文件中定义的所需字体。(instructions on adding a custom font are here)示例
字符串
下面的图片显示了当languageCode为“en”(左)时,主题设置为默认字体,而其他区域设置为自定义字体(右)。
100d1x
的字符串
raogr8fs2#
您可以监听设备区域设置更改并分别更改字体系列。
bxpogfeg3#
有一个“fontFamilyFallback”属性,它接受字符串列表(字体名称)示例:
字符串