在你的应用中动态加载翻译。

入门

在你的dart的main() {} 中初始化I18n。

void main() {
    // ...

    I18n.init(
        url: 'https://www.example.com',
        locale: 'hi',
        locales: ['en', 'hi', 'pa'],
    );

    // ... 
}

现在你可以在你的代码中的任何地方使用I18n.builder

Column(
    children: [
        // example 1: for Text
        I18n.text('Who am I ?'), // Text('मैं कौन हूँ ?')

        // example 2: with builder
        // first build with given locale
        // rebuild after translation fetching
        I18n.builder('Who am I ?', (translatedText) {
            return Text(translatedText);
        }),

        // example 3: with childBuilder
        I18n.childBuilder(
            'Who am I ?',
            (translatedText, child) {
                return Column(
                children: [
                    Text(translatedText),
                    child, // same on both first and second build
                ],
                );
            },
            Container(), // will be reused in rebuild
        ),
    ],
);

服务器设置

设置你的服务器以这种方式响应。

请求方法: GET
请求URL: https://www.example.com/hi.json

响应
Content-Type: application/json

[
    {'en': 'How are you ?', 'hi': 'आप कैसे हो ?'},
    {'en': 'Who am I ?', 'hi': 'मैं कौन हूँ ?'},
]

对于单个翻译请求,库将以这种格式向你提供的url发送POST请求,根据上面的示例,它将是

请求方法: POST
请求URL: https://www.example.com/hi

{
    'en': sourceText,
    'target': targetLocale,
}

响应
Content-Type: application/json

{'en': 'How are you ?', 'hi': 'आप कैसे हो ?'}

GitHub

查看 Github