You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何免费为Flutter应用添加多语言支持及API数据预翻译?

Flutter多语言支持全指南:应用切换+数据库内容翻译+免费方案

Great question! Let's walk through how to tackle each of your requirements step by step—app-wide language switching, translating database-fetched content, and free translation options that work seamlessly with Flutter.

1. 实现全应用语言切换

The go-to approach here combines Flutter's built-in flutter_localizations package with a state management tool (like provider or GetX) to handle real-time locale changes.

Step 1: Add dependencies

First, drop these into your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  provider: ^6.0.0 # Or your preferred state manager

Step 2: Configure app localization

In main.dart, set up your MaterialApp to support target languages:

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'language_provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => LanguageProvider(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final languageProvider = Provider.of<LanguageProvider>(context);
    
    return MaterialApp(
      locale: languageProvider.currentLocale,
      supportedLocales: [
        const Locale('en', 'US'), // English
        const Locale('es', 'ES'), // Spanish
        const Locale('zh', 'CN'), // Chinese
        // Add more locales as needed
      ],
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        AppLocalizations.delegate, // Generated custom delegate
      ],
      home: HomeScreen(),
    );
  }
}

Step 3: Create translation files

Make a l10n folder with JSON files for each language, e.g., app_en.json, app_zh.json:

// app_en.json
{
  "welcome": "Welcome!",
  "settings": "Settings"
}

// app_zh.json
{
  "welcome": "欢迎!",
  "settings": "设置"
}

Run flutter gen-l10n to generate the localization class (enable generate: true in pubspec.yaml under the flutter section first).

Step 4: Add language switching logic

Build a LanguageProvider to manage the active locale:

import 'package:flutter/material.dart';

class LanguageProvider extends ChangeNotifier {
  Locale _currentLocale = const Locale('en', 'US');

  Locale get currentLocale => _currentLocale;

  void setLocale(Locale locale) {
    _currentLocale = locale;
    notifyListeners();
  }
}

Then add a UI control (like a dropdown in settings) to trigger the switch:

DropdownButton<Locale>(
  value: Provider.of<LanguageProvider>(context).currentLocale,
  items: [
    DropdownMenuItem(
      value: const Locale('en', 'US'),
      child: Text('English'),
    ),
    DropdownMenuItem(
      value: const Locale('zh', 'CN'),
      child: Text('中文'),
    ),
  ],
  onChanged: (Locale? newLocale) {
    if (newLocale != null) {
      Provider.of<LanguageProvider>(context, listen: false).setLocale(newLocale);
    }
  },
)

2. 翻译数据库获取的数据

How you handle this depends on what your database stores:

Case 1: Database stores translation keys

If your DB returns keys like welcome instead of raw text, use your existing localization setup directly:

// Fetch key from database
String dbKey = await fetchFromDatabase();
// Get translated text
String translatedText = AppLocalizations.of(context)!.translate(dbKey);

Case 2: Database stores dynamic content (e.g., user-generated text)

For dynamic text, call a translation API when fetching data, using the app's current locale. Here's a quick example:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<String> translateText(String text, String targetLang) async {
  // Replace with your chosen API endpoint
  final response = await http.post(
    Uri.parse('YOUR_TRANSLATION_API_ENDPOINT'),
    body: {
      'text': text,
      'target': targetLang,
    },
  );
  
  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    return data['translatedText'];
  } else {
    // Fallback to original text if translation fails
    return text;
  }
}

// Usage when fetching dynamic content
String rawText = await fetchDynamicContentFromDB();
String targetLang = Provider.of<LanguageProvider>(context).currentLocale.languageCode;
String translatedText = await translateText(rawText, targetLang);

Pro tip: Cache translated results (using shared_preferences or a local database) to avoid repeated API calls and save on quota.

3. 免费的Flutter应用翻译方案

Here are reliable free options that integrate smoothly with Flutter:

  • Google Translate API: Offers a limited free tier for non-commercial use, perfect for smaller apps with moderate translation needs.
  • LibreTranslate: Open-source, self-hostable translation service. You can use public instances for free or deploy your own—no API key required for public access, and it supports 50+ languages.
  • DeepL Free API: Provides a generous free tier (up to 500,000 characters/month) with high-quality translations, ideal for accurate results in common languages.
  • MyMemory Translator: Free for non-commercial use with a daily request limit. It crowdsources translations, making it useful for less common languages.

Key tips for free APIs

  • Always handle rate limits and errors gracefully (fall back to the original text if translation fails).
  • Cache translations to minimize API calls and reduce latency.
  • Review each service's terms of service to ensure compliance with your app's use case.

内容的提问来源于stack exchange,提问作者Srajan Gupta

火山引擎 最新活动