flutter: Unhandled Exception: Unable to load asset: assets/languages/en
Asked Answered
T

1

6

i am using flutter localization, and i have added my language and parameters to be translated as json files for each language.. the language json files are in a folder called asset from the root folder like this

enter image description here

and i also declared it in my pubspec.yaml like this

enter image description here

also here's my code for the en json:

{
  "home_title": "Welcome To Tamata! \nThe online supermarket"
}

here's my material app :

MaterialApp(
        locale: _locale,
        supportedLocales: [
          Locale('en', 'US'),
          Locale('ar', ''),
//          Locale('ar', 'IQ'),
        ],
        localizationsDelegates: [
          DemoLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        localeResolutionCallback: (deviceLocale, supportedLocales) {
          for (var locale in supportedLocales) {
            if (locale.languageCode == deviceLocale.languageCode &&
                locale.countryCode == deviceLocale.countryCode) {
              return deviceLocale;
            }
          }
          return supportedLocales.first;
        },
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
            primaryColor: Color(0xffba0100),
            accentColor: Color(0xff188949),
            canvasColor: Colors.grey[100],
            textTheme: TextTheme().copyWith(
              bodyText1: TextStyle(
                color: Colors.white,
                fontSize: 17.0,
                fontWeight: FontWeight.w700,
              ),
              bodyText2: TextStyle(
                color: Colors.white,
              ),
              headline6: TextStyle(
                color: Colors.black,
                fontSize: 18.0,
              ),
            )),
        title: 'Tamata Online',
        initialRoute: '/',
        routes: {
          '/': (ctx) => LoadingScreen(
              initScreen), //TODO put it back to be LoadingScreen(initScreen)
          TabsScreen.id: (ctx) => TabsScreen(
                filteredBySearch: filteredBySearch,
                filteredBySpecialSearch: filteredBySpecialSearch,
              ),
          SettingsScreen.id: (ctx) => SettingsScreen(),
          CartScreen.id: (ctx) => CartScreen(),
          IntroScreen.id: (ctx) => IntroScreen(),
          ChooseLanguageScreen.id: (ctx) => ChooseLanguageScreen(),
          SpecialOffers.id: (ctx) => SpecialOffers(),
        },
      ),

and here is my demo localization :

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class DemoLocalizations {
  final Locale locale;

  DemoLocalizations(this.locale);

  static DemoLocalizations of(BuildContext context) {
    return Localizations.of<DemoLocalizations>(context, DemoLocalizations);
  }

  Map<String, String> _localizedValues;

  Future load() async {
    String jsonStringValues =
        await rootBundle.loadString('assets/languages/${locale.languageCode}'); //where it says it has a problem reading my assets/language/en

    Map<String, dynamic> mappedJson = jsonDecode(jsonStringValues);
    _localizedValues =
        mappedJson.map((key, value) => MapEntry(key, value.toString()));
  }

  String getTranslatedValue(String key) {
    return _localizedValues[key];
  }

  static const LocalizationsDelegate<DemoLocalizations> delegate =
      _DemoLocalizationDelegate();
}

class _DemoLocalizationDelegate
    extends LocalizationsDelegate<DemoLocalizations> {
  const _DemoLocalizationDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['en', 'ar'].contains(locale.languageCode);
  }

  @override
  Future<DemoLocalizations> load(Locale locale) async {
    DemoLocalizations localization = DemoLocalizations(locale);
    await localization.load();
    return localization;
  }

  @override
  bool shouldReload(_DemoLocalizationDelegate old) => false;
}

what am i doing wrong?

here's the error:

Unable to load asset: assets/languages/en
E/flutter (19559): #0      PlatformAssetBundle.load
Truffle answered 5/7, 2020 at 16:54 Comment(0)
H
5

Since your localization files are in JSON format, you'll need to add .json to your file path.

Future load() async {
    String jsonStringValues =
        await rootBundle.loadString('assets/languages/${locale.languageCode}.json'); // add .json at the end

    Map<String, dynamic> mappedJson = jsonDecode(jsonStringValues);
    _localizedValues =
        mappedJson.map((key, value) => MapEntry(key, value.toString()));
  }
Hone answered 5/7, 2020 at 17:3 Comment(1)
thankyou so much! this worked for me, idk whyi have tried this before and it didn't work, ig i put the json somewhere else but now its working! thankyouTruffle

© 2022 - 2024 — McMap. All rights reserved.