admin管理员组

文章数量:1122846

I'm developing a Flutter app that needs to handle translations for both static text in widgets and dynamic text coming from an API. I've set up a translation provider using the translator package, but manually updating hundreds of files for translation is not feasible. Here’s what I’ve done so far:

Current Setup

  1. TranslationProvider: I created a TranslationProvider to manage translations.

    import 'package:flutter/cupertino.dart';
    import 'package:translator/translator.dart';
    import 'language_util.dart';
    import 'ui_text.dart';
    
    class TranslationProvider with ChangeNotifier {
      String _translatedText = "";
      String _selectedLanguage = 'en';
      final GoogleTranslator _translator = GoogleTranslator();
      final LanguagePreferences _prefs = LanguagePreferences();
      Map<String, String> _translatedUITexts = {};
    
      String get translatedText => _translatedText;
      String get selectedLanguage => _selectedLanguage;
      Map<String, String> get translatedUITexts => _translatedUITexts;
    
      TranslationProvider() {
        loadSavedLanguage();
      }
    
      void loadSavedLanguage() async {
        _selectedLanguage = await _prefs.getLanguageCode();
        translateUITexts(uiTexts);
        notifyListeners();
      }
    
      Future<void> translateText(String input) async {
        if (input.isNotEmpty) {
          final translation = await _translator.translate(input, from: 'en', to: _selectedLanguage);
          _translatedText = translation.text;
          notifyListeners();
        }
      }
    
      void changeLanguage(String langCode) async {
        _selectedLanguage = langCode;
        await _prefs.setLanguageCode(langCode);
        translateUITexts(uiTexts);
        notifyListeners();
      }
    
      Future<void> translateUITexts(Map<String, String> uiTexts) async {
        Map<String, String> translatedTexts = {};
        for (String key in uiTexts.keys) {
          final translation = await _translator.translate(uiTexts[key]!, from: 'en', to: _selectedLanguage);
          translatedTexts[key] = translation.text;
        }
        _translatedUITexts = translatedTexts;
        notifyListeners();
      }
    
      Future<String> translateApiText(String text) async {
        if (text.isNotEmpty) {
          final translation = await _translator.translate(text, from: 'en', to: _selectedLanguage);
          return translation.text;
        }
        return text;
      }
    
      Future<List<String>> translateApiTexts(List<String> texts) async {
        List<String> translatedTexts = [];
        for (String text in texts) {
          final translation = await _translator.translate(text, from: 'en', to: _selectedLanguage);
          translatedTexts.add(translation.text);
        }
        return translatedTexts;
      }
    }
    
  2. Static Content Translation: For static content, I use a map to store the texts.

    final Map<String, String> uiTexts = {
      'page1_title': 'Tej',
      'page2_title': 'Page 2 Title',
      'page3_title': 'Page 3 Title',
      'hintText': 'Enter text to translate',
      'translateButton': 'Translate',
      'translatedText': 'Translated Text:',
    };
    
    Text(provider.translatedUITexts['page1_title'] ?? 'Page 1 Title');
    
  3. Dynamic Content Translation: For API data, I use FutureBuilder to handle translations.

    FutureBuilder<String>(
      future: provider.translateApiText(consumerName),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        } else if (snapshot.hasError) {
          return CustomText(
            text: "Error translating text",
            color: AppColors.white,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          );
        } else {
          return CustomText(
            text: "${provider.translatedUITexts['Dashboard_Hello'] ?? 'Hello'} ${snapshot.data ?? consumerName}",
            color: AppColors.white,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          );
        }
      },
    );
    

The Problem

Manually updating hundreds of files for translation is time-consuming. Is there an efficient way to handle both static and dynamic text translations across the app without manually updating each Text widget?

What I'm Looking For

  • A streamlined method to translate static texts without individually updating each widget.
  • A way to automate the translation of dynamic content received from APIs.
  • Best practices for integrating this into a Flutter app.

Any help or guidance would be greatly appreciated!

本文标签: localizationHow to Efficiently Translate Static and Dynamic Text in a Flutter AppStack Overflow