首页 > 解决方案 > 颤振本地路线问题

问题描述

我对颤动的本地应用程序有一个小问题。我试图根据设备语言代码有 2 条路线。当我构建应用程序时,会启动第二个选项。如果我保存应用程序,则会选择正确的路线。我觉得

final lang = locale.languageCode;

调用时没有值:

"/newsfeed": lang == "da"
              ? (BuildContext context) => News()
              : (BuildContext context) => NewsEN(),

我在代码中的打印语句具有正确的值,所以有点丢失这里是代码:

class MyApp3 extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        // List all of the app's supported locales here
        supportedLocales: [
          Locale('en', 'US'),
          Locale('da', 'DK'),
        ],
        // These delegates make sure that the localization data for the proper language is loaded
        localizationsDelegates: [
          // A class which loads the translations from JSON files
          AppLocalizations.delegate,
          // Built-in localization of basic text for Material widgets
          GlobalMaterialLocalizations.delegate,
          // Built-in localization for text direction LTR/RTL
          GlobalWidgetsLocalizations.delegate,
        ],
        // Returns a locale which will be used by the app
        localeResolutionCallback: (locale, supportedLocales) {
          // Check if the current device locale is supported
          for (var supportedLocale in supportedLocales) {
            //print(locale.languageCode);


            final lang = locale.languageCode;
            print(lang);
            if (supportedLocale.languageCode == locale.languageCode &&
                supportedLocale.countryCode == locale.countryCode) {

              return supportedLocale;
            }
          }
          // If the locale of the device is not supported, use the first one
          // from the list (English, in this case).
          return supportedLocales.first;
        },
        home: MyHomePage(),
        routes: <String, WidgetBuilder> {
          //"/Knowledge_pick": (BuildContext context) => SplashScreen(),
          "/calculator_pick": (BuildContext context) => Pickcalculator(),
          //"/receipe_pick": (BuildContext context) => Receipemenu(),
            "/receipe_pick": (BuildContext context) => Wrapper(),
          "/newsfeed": lang == "da"
              ? (BuildContext context) => News()
              : (BuildContext context) => NewsEN(),

希望有人可以帮助我解决这个问题。

标签: flutterlocalization

解决方案


老实说,我不明白为什么这行不通,但是您应该尝试设置两条不同的路线,一条来自“da”,一条用于“en”

"/newsfeedDA": (BuildContext context) => News(),
"/newsfeedEN": (BuildContext context) => NewsEN(),

并在 MyHomePage() 的 initState 或构造函数中选择它们的逻辑。


推荐阅读