Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android flatter中的字符串xml文件_Android_Dart_Resources_Flutter - Fatal编程技术网

Android flatter中的字符串xml文件

Android flatter中的字符串xml文件,android,dart,resources,flutter,Android,Dart,Resources,Flutter,在颤振字符串中,文本直接设置为TextField小部件,如: new Text('Hello, How are you?') 正确的方法是什么?或者我们可以在一个文件中维护所有字符串,并使用它,如: <string name="name_hint">Hello, How are you?</string> 你好,你好吗? 可能吗?这是正确的方法。在flatter中,您不需要.xml或.css文件来管理布局/内容 一切都使用dart代码进行管理。这使一切变得更容易。

在颤振字符串中,文本直接设置为
TextField
小部件,如:

new Text('Hello,  How are you?')
正确的方法是什么?或者我们可以在一个文件中维护所有字符串,并使用它,如:

<string name="name_hint">Hello, How are you?</string>
你好,你好吗?
可能吗?

这是正确的方法。在flatter中,您不需要
.xml
.css
文件来管理布局/内容


一切都使用dart代码进行管理。这使一切变得更容易。

您可以使用文档国际化部分中表示的方法来控制集中的字符串管理和翻译(如果您需要翻译)


不过,对于一个只有几个字符串的简单应用程序来说,这可能有些过头了。

flatter目前没有专门的资源,比如字符串系统。目前,最好的做法是将复制文本作为静态字段保存在类中,并从那里访问它们。例如:

class Strings {
  static const String welcomeMessage = "Welcome To Flutter";
}
然后在代码中,您可以访问字符串:

Text(Strings.welcomeMessage)


编辑19年5月:

现在有了一个可以使用字符串创建json文件的工具。它将允许您为复数、性别和语言等创建字符串

您可以为每种语言创建单独的json文件,如下所示:

string_en.json

string_nl.json

然后用这个来访问它

S.of(context).thanks;
它将根据您手机的默认语言知道选择哪种语言

  create "Strings.dart" file and add the below line==>


 class Strings
 {
      static String welcomeScreen="WelCome Page";
      static String loadingMessage="Loading Please Wait...!";
 }

 And then call the file using the below line using the widget
 Text(Strings.loadingMessage)

 Make sure that the String.dart file has been imported
对于那些不想使用任何第三方插件的人,这里介绍了如何做到这一点

  • assets
    中创建文件夹
    strings
    。把你的语言文件放进去

    assets
      strings
      - en.json // for english 
      - ru.json  // for russian
    
  • 现在在
    en.json
    中,编写您的字符串,例如

    {
      "text1": "Hello",
      "text2": "World"
    }
    
    类似地,在
    ru.json

    {
      "text1": "Привет",
      "text2": "Мир"
    }
    
  • 将此添加到
    pubspec.yaml
    文件(注意空格)

  • 现在,您已准备好在应用程序中使用这些字符串。下面是示例代码,
    AppBar
    显示翻译后的文本

    void main() {
      runApp(
        MaterialApp(
          locale: Locale("ru"), // switch between en and ru to see effect
          localizationsDelegates: [const DemoLocalizationsDelegate()],
          supportedLocales: [const Locale('en', ''), const Locale('ru', '')],
          home: HomePage(),
        ),
      );
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text(DemoLocalizations.of(context).getText("text2") ?? "Error")),
        );
      }
    }
    
    // this class is used for localizations
    class DemoLocalizations {
      static DemoLocalizations of(BuildContext context) {
        return Localizations.of<DemoLocalizations>(context, DemoLocalizations);
      }
    
      String getText(String key) => language[key];
    }
    
    Map<String, dynamic> language;
    
    class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations> {
      const DemoLocalizationsDelegate();
    
      @override
      bool isSupported(Locale locale) => ['en', 'ru'].contains(locale.languageCode);
    
      @override
      Future<DemoLocalizations> load(Locale locale) async {
        String string = await rootBundle.loadString("assets/strings/${locale.languageCode}.json");
        language = json.decode(string);
        return SynchronousFuture<DemoLocalizations>(DemoLocalizations());
      }
    
      @override
      bool shouldReload(DemoLocalizationsDelegate old) => false;
    }
    
    void main(){
    runApp(
    材料聚丙烯(
    locale:locale(“ru”),//在en和ru之间切换以查看效果
    LocalizationsDelegate:[const DemoLocalizationsDelegate()],
    支持的语言环境:[常量语言环境('en',''),常量语言环境('ru','')],
    主页:主页(),
    ),
    );
    }
    类主页扩展了无状态小部件{
    @凌驾
    小部件构建(构建上下文){
    返回脚手架(
    appBar:appBar(标题:Text(DemoLocalizations.of(context).getText(“text2”)??“Error”),
    );
    }
    }
    //此类用于本地化
    阶级去本地化{
    (BuildContext上下文)的静态去本地化{
    返回本地化。of(上下文,去本地化);
    }
    字符串getText(字符串键)=>语言[key];
    }
    地图语言;
    类DemoLocalizationsDelegate扩展了LocalizationsDelegate{
    常量DemoLocalizationsDelegate();
    @凌驾
    bool isSupported(Locale)=>['en','ru'].contains(Locale.languageCode);
    @凌驾
    未来加载(区域设置)异步{
    String String=await rootBundle.loadString(“assets/strings/${locale.languageCode}.json”);
    language=json.decode(字符串);
    返回SynchronousFuture(DemoLocalizations());
    }
    @凌驾
    bool应该重新加载(DemoLocalizationsDelegate old)=>false;
    }
    

  • 我使用这个方法,而不是使用第三方库。基本上,我创建了一个类来保存这些值(字符串、颜色、尺寸等)

    资源,省道

    import 'dart:ui';
    
    class ResString{
      var data = {
        'url' : 'https://facebook.com/',
        'welcome' : 'Welcome Home',
      };
    
      String get(String key){
        return data[key];
      }
    }
    
    class ResColor{
      var data = {
        'colorPrimary' : 0xff652A04,
        'colorPrimaryDark' : 0xffFFFFFF,
        'colorPrimaryLight' : 0xffF6EDDD,
      };
    
      Color get(String key){
        return Color(data[key]);
      }
    }
    
    要使用它,只需调用get方法

    主飞镖

    import 'package:my_app/resources.dart';
    ...
        return Container(
          color: ResColor().get('colorPrimary')
        );
    ...
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          navigatorKey: Application.navKey,
    ...
    

    我会将这些类划分为单独的文件,但只是为了解释我解决这个问题的方法

    我有一个基类,它有我的字符串获取程序。我想要支持的每种语言都必须创建一个从这个类扩展而来的类,并重写它的getter。因此,每当我创建一个字符串时,我必须重写这个基类的每个实现。这有助于避免忘记创建特定于语言环境的字符串

    /// Interface strings
    class Strings {
    
      String get hello;
    }
    
    
    /// English strings
    class EnglishStrings extends Strings {
       
      @override
      String get hello => 'Hello';
    }
    
    /// Russian strings
    class RussianStrings extends Strings {
      @override
      String get hello => 'Привет';
    }
    
    /// Portuguese strings
    class PortugueseStrings extends Strings {
      @override
      String get hello => 'Olá';
    }
    
    之后,在应用程序的全局范围内,您可以声明要使用的区域设置的唯一实例(使用单例是一个不错的选择)

    仅举一个使用它的简短示例:

     class Resources {
      BuildContext _context;
    
      Resources(this._context);
    
      Strings get strings {
        // It could be from the user preferences or even from the current locale
        Locale locale = Localizations.localeOf(_context);
        switch (locale.languageCode) {
          case 'pt':
            return PortugueseStrings();
          case 'ru':
            return RussianStrings();
          default:
            return EnglishStrings();
        }
      }
    
      static Resources of(BuildContext context){
        return Resources(context);
      }
    }
    
    最后,在一些小部件中使用它:

    Text(Resources.of(context).strings.hello)
    
    使用BuildContext的扩展

    您可以扩展BuildContext来创建一些特定功能,并为应用程序提供更多功能。 这可从Dart 2.7中获得

    app\u context\u extension.dart

    extension AppContext on BuildContext {
    
      Resources get resources => Resources.from(this);
    
    }
    
    收藏夹\u page.dart

    import 'package:flutter/material.dart';
    // you have to import it yourself. The auto import does not work in this case
    import 'package:myapp/ui/extensions/app_context_extension.dart';
    
    class FavoritesPage extends StatefulWidget {
      @override
      _FavoritesPageState createState() => _FavoritesPageState();
    }
    
    class _FavoritesPageState extends State<FavoritesPage> {
      @override
      Widget build(BuildContext context) {
        return Text(context.resources.strings.hello);
      }
    }
    
    然后:

    import 'package:flutter/material.dart';
    import 'package:myapp/application/application.dart';
    
    class FavoritesPage extends StatefulWidget {
      @override
      _FavoritesPageState createState() => _FavoritesPageState();
    }
    
    class _FavoritesPageState extends State<FavoritesPage> {
      @override
      Widget build(BuildContext context) {
        return Text(Application.resources.strings.hello);
      }
    }
    
    导入“包装:颤振/材料.省道”;
    导入“包:myapp/application/application.dart”;
    类FavoritesPage扩展StatefulWidget{
    @凌驾
    _FavoriteSpegate createState()=>_FavoriteSpegate();
    }
    类_favoriteSpegate扩展状态{
    @凌驾
    小部件构建(构建上下文){
    返回文本(Application.resources.strings.hello);
    }
    }
    

    希望有帮助

    管理这些语言一点也不好笑,Android Studio有一个内置的Transalte插件,可以让你轻松地管理这些单词,因此你可以在表格中看到单词的关键字,以及你刚刚添加的每种语言的结果,当然是手动的。我希望很快就会飞起来

    您想实现什么?Xou可以添加JSON文件或(Dart中不太常见的XML文件)如果你想用不同的语言维护字符串,可以使用
    intl
    软件包。例如,在android中,我将所有字符串都维护在一个xml中,我也可以重用。这就是为什么我要问,在Flatter中是否可能?但我如何将相同的字符串重用到另一个文本小部件?你可以创建全局常量问题在于本地化。可能可以通过将其设置为单例来改进。我建议将每个字符串
    static const
    如何与英语和法语一起使用此样式?这将不允许进行语言翻译。它只是为您的字符串创建一个God类
    import 'package:flutter/material.dart';
    // you have to import it yourself. The auto import does not work in this case
    import 'package:myapp/ui/extensions/app_context_extension.dart';
    
    class FavoritesPage extends StatefulWidget {
      @override
      _FavoritesPageState createState() => _FavoritesPageState();
    }
    
    class _FavoritesPageState extends State<FavoritesPage> {
      @override
      Widget build(BuildContext context) {
        return Text(context.resources.strings.hello);
      }
    }
    
    import 'package:myapp/ui/extensions/app_context_extension.dart';
    import 'package:myapp/ui/values/resources.dart';
    import 'package:flutter/material.dart';
    
    class Application {
      static GlobalKey<NavigatorState> navKey = GlobalKey();
    
      static Resources get resources {
        return navKey.currentContext.resources;
      }
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          navigatorKey: Application.navKey,
    ...
    
    import 'package:flutter/material.dart';
    import 'package:myapp/application/application.dart';
    
    class FavoritesPage extends StatefulWidget {
      @override
      _FavoritesPageState createState() => _FavoritesPageState();
    }
    
    class _FavoritesPageState extends State<FavoritesPage> {
      @override
      Widget build(BuildContext context) {
        return Text(Application.resources.strings.hello);
      }
    }