custom assets loaders for easy_localization

Overview

Custom assets loaders for Easy Localization package

Pub Version Code Climate issues GitHub closed issues GitHub contributors GitHub repo size GitHub forks GitHub stars

CodeFactor Grade GitHub license

Supported formats

  • JSON (JsonAssetLoader)
  • CSV (CsvAssetLoader)
  • HTTP (HttpAssetLoader)
  • XML (XmlAssetLoader, XmlSingleAssetLoader)
  • Yaml (YamlAssetLoader, YamlSingleAssetLoader)
  • FILE (FileAssetLoader)

Configuration

  1. Add this to your package's pubspec.yaml file:
dependencies:
  #Easy Localization main package
  easy_localization: <last_version>

    # stable version install from https://pub.dev/packages
  easy_localization_loader: <last_version>

  # Dev version install from git REPO
  easy_localization_loader:
    git: https://github.com/aissat/easy_localization_loader.git
  1. Change assetLoader and patch
...
void main(){
  runApp(EasyLocalization(
    child: MyApp(),
    supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')],
    path: 'resources/langs/langs.csv',
    assetLoader: CsvAssetLoader()
  ));
}
...
  1. All done!.
Comments
  • fixing: Because easy_localization_loader >=0.0.1 depends on xml ^3.5.…

    fixing: Because easy_localization_loader >=0.0.1 depends on xml ^3.5.…

    …0 and flutter_svg 0.18.0 depends on xml ^4.1.0, easy_localization_loader >=0.0.1 is incompatible with flutter_svg 0.18.0. So, because qanuni_mobile_app depends on both flutter_svg 0.18.0 and easy_localization_loader 0.0.2, version solving failed.

    opened by FarooqQaisrani 8
  • easy_localization_loader ^0.0.2 is incompatible with flutter_svg >=0.18.0

    easy_localization_loader ^0.0.2 is incompatible with flutter_svg >=0.18.0

    Because no versions of easy_localization_loader match >0.0.2 <0.1.0 and easy_localization_loader 0.0.2 depends on xml ^3.5.0, easy_localization_loader ^0.0.2 requires xml ^3.5.0. Because flutter_svg >=0.18.1 depends on xml ^4.2.0 and flutter_svg >=0.18.0 <0.18.1 depends on xml ^4.1.0, flutter_svg >=0.18.0 requires xml ^4.1.0. Thus, easy_localization_loader ^0.0.2 is incompatible with flutter_svg >=0.18.0. So, because cip depends on both flutter_svg ^0.18.0 and easy_localization_loader ^0.0.2, version solving failed. Running "flutter pub get" in cip...
    pub get failed (1; So, because cip depends on both flutter_svg ^0.18.0 and easy_localization_loader ^0.0.2, version solving failed.)

    opened by Ya-seeen 7
  • feature/smart-network-loader

    feature/smart-network-loader

    Purpose

    • add new class SmartNetworkAssetLoader that able to fetch localization using online .json files from provided url.
    • add configurable cache from network assets using Duration(..) class
    • add Failover system to local assets when there is a failure when fetching the online .json and no caches stored
    • inspired by and resolved #30 , #29 , #17

    Types of changes

    What types of changes does your code introduce? Put an x in the boxes that apply

    • [ ] Bugfix (non-breaking change which fixes an issue)
    • [X] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [ ] Documentation Update (if none of the other choices apply)

    How to Test

    Just use this class in the assetLoader attribute of EasyLocalization and configure it as you want

    SmartNetworkAssetLoader(
              assetsPath: 'assets/translations',
              localCacheDuration: Duration(days: 1),
              localeUrl: (String localeName) => Constants.appLangUrl,
              timeout: Duration(seconds: 30)
    )
    

    Environment

    Please define your environment to test this, you can choose multiple options. Put an x in the boxes that apply

    • [X] Production
    • [X] Development
    • [X] Testing
    • [X] Android
    • [X] iOS
    Attach your `flutter doctor -v` inside code block:

    [✓] Flutter (Channel stable, 2.5.3, on macOS 12.3.1 21E258 darwin-arm, locale en-ID)
        • Flutter version 2.5.3 at /Users/ariefwijaya/fvm/versions/2.5.3
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 18116933e7 (6 months ago), 2021-10-15 10:46:35 -0700
        • Engine revision d3ea636dc5
        • Dart version 2.14.4
    
     [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0-rc2)
        • Android SDK at /Users/ariefwijaya/Library/Android/sdk
        • Platform android-31, build-tools 33.0.0-rc2
        • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Xcode 13.3.1, Build version 13E500a
        • CocoaPods version 1.11.2
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2021.1)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    
    [✓] IntelliJ IDEA Community Edition (version 2020.3.4)
        • IntelliJ at /Applications/IntelliJ IDEA CE.app
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
    
    [✓] VS Code (version 1.66.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.38.1
    
    [✓] Connected device (1 available)
        • Chrome (web) • chrome • web-javascript • Google Chrome 100.0.4896.127
    
    • No issues found!
    

    Expected Results

    1. able to fetch localization data from provided url, otherwise get data from assetsPath
    2. When the data has been fetched, it can be use even in offline because caches system
    opened by ariefwijaya 6
  • HTTP parameters for SmartNetworkLoader

    HTTP parameters for SmartNetworkLoader

    Sometimes it's needed to specify additional parameters for an HTTP request. In my case I need to pass an api token in the header to be able to get access to my localization service (Localizely). Currently the loader takes String URL. I think it would be better to change it to HTTP object instead, so user can shape the request as he\she needs. Just a suggestion.

    opened by Floul 3
  • [Important][Suggestion] Please upgrade http

    [Important][Suggestion] Please upgrade http

    Hello, I wanted to update the libraries I installed on my mobile application, but when I put the latest version of http, it tells me that easy_localization_loader is dependent on http ^0.12.0+2

    Here is the entire error:

    Because every version of easy_localization_loader depends on http ^0.12.0+2 and hover depends on http ^0.13.0, easy_localization_loader is forbidden.
    
    So, because hover depends on easy_localization_loader ^0.0.2, version solving failed.
    pub get failed (1; So, because hover depends on easy_localization_loader ^0.0.2, version solving failed.)
    exit code 1
    

    Can you change the version of http?

    opened by iok42 3
  • [Question] How JSON loader is working?

    [Question] How JSON loader is working?

    https://github.com/aissat/easy_localization_loader/blob/master/lib/src/json_asset_loader.dart

    I do not understand how you can load data from json file as the json asset_loader is not implemented?

    Maybe the file asset loader is more appropriate as it contain "jsondecode" ?

    https://github.com/aissat/easy_localization_loader/blob/master/lib/src/file_asset_loader.dart

    opened by Maus3rSR 2
  • AssetOrNetworkAssetLoader

    AssetOrNetworkAssetLoader

    I want to solve this issue please.....

    this library can be support getting locale from network when its available?

    it seems this class don't work correctly and i get some error. reference

    final String assetsLocalePath = 'assets/langs/';
        runApp(EasyLocalization(
          path: assetsLocalePath,
          useOnlyLangCode: true,
          child: MyApp(),
          assetLoader: AssetOrNetworkAssetLoader(
              assetsPath: assetsLocalePath,
              localCacheDuration: Duration(days: 1), // how long the localizations file should be kept
              localeUrl: (String localeName) =>  'http://example.com/$localeName'), // the URL for the remote locale file
          supportedLocales:
              supportedLocales.map((locale) => Locale(locale)).toList(),
    

    The loader:

    import 'dart:async';
    import 'dart:convert';
    import 'dart:io';
    
    import 'package:connectivity/connectivity.dart';
    import 'package:easy_localization/easy_localization.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:http/http.dart' as http;
    import 'package:path_provider/path_provider.dart';
    
    const defaultTimeout = Duration(seconds: 1);
    
    class AssetOrNetworkAssetLoader extends AssetLoader {
      /// The local URL method which accepts a [localeName] and returns the full distant
      /// localUrl
      final Function localeUrl;
    
      /// The timeout for downloading the distant localization files
      final Duration timeout;
    
      /// The default path for assets json files
      final String assetsPath;
    
      /// The duration before refreshing local localizations files with distant ones
      final Duration localCacheDuration;
    
      AssetOrNetworkAssetLoader(
          {@required this.localeUrl,
          this.timeout,
          this.assetsPath,
          this.localCacheDuration});
    
      @override
      Future<Map<String, dynamic>> load(String localePath) async {
        String string;
        String localeName =
            localePath.replaceFirst(assetsPath, '').replaceFirst('.json', '');
    
        // try loading local previously-saved localization file
        if (await localTranslationExists(localeName)) {
          string = await loadFromLocalFile(localeName);
        }
    
        // no local or failed, check if internet and download the file
        if (string == null && await isInternetConnectionAvailable()) {
          string = await loadFromNetwork(localeName);
        }
    
        // local cache duration was reached or no internet access but prefer local file to assets
        if (string == null &&
            await localTranslationExists(localeName, ignoreCacheDuration: true)) {
          string = await loadFromLocalFile(localeName);
        }
    
        // still nothing? Load from assets
        if (string == null) {
          string = await rootBundle.loadString(localePath);
        }
    
        // then returns the json file
        return json.decode(string);
      }
    
      @override
      Future<bool> localeExists(String localePath) => Future.value(true);
    
      Future<bool> isInternetConnectionAvailable() async {
        ConnectivityResult connectivityResult =
            await (Connectivity().checkConnectivity());
        if (connectivityResult == ConnectivityResult.none) return false;
    
        final result = await Future.any([
          InternetAddress.lookup('example.com'),
          Future.delayed(timeout ?? defaultTimeout)
        ]);
    
        if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
          return true;
        }
    
        return false;
      }
    
      Future<String> loadFromNetwork(String localeName) async {
        String url = localeUrl(localeName);
    
        try {
          final response = await Future.any(
              [http.get(url), Future.delayed(timeout ?? defaultTimeout)]);
    
          if (response != null && response.statusCode == 200) {
            String content = response.body.toString();
    
            // check valid json before saving it
            if (json.decode(content) != null) {
              await saveTranslation(localeName, content);
              return content;
            }
          }
        } catch (e) {
          print(e.toString());
        }
    
        return null;
      }
    
      Future<bool> localTranslationExists(String localeName,
          {bool ignoreCacheDuration: false}) async {
        File translationFile = await getFileForLocale(localeName);
    
        if (!await translationFile.exists()) {
          return false;
        }
    
        // don't check file's age
        if (!ignoreCacheDuration) {
          Duration difference =
              DateTime.now().difference(await translationFile.lastModified());
    
          if (difference > (localCacheDuration ?? Duration(days: 1))) {
            return false;
          }
        }
    
        return true;
      }
    
      Future<String> loadFromLocalFile(String localeName) async {
        return await (await getFileForLocale(localeName)).readAsString();
      }
    
      Future<void> saveTranslation(String localeName, String content) async {
        File file = await new File(await getFilenameForLocale(localeName))
            .create(recursive: true);
        return file.writeAsString(content);
      }
    
      Future<String> get _localPath async {
        final directory = await getTemporaryDirectory();
    
        return directory.path;
      }
    
      Future<String> getFilenameForLocale(String localeName) async {
        return "${await _localPath}/langs$localeName.json";
      }
    
      Future<File> getFileForLocale(String localeName) async {
        return File(await getFilenameForLocale(localeName));
      }
    }
    
    opened by mjubouri 1
  • new parsers

    new parsers

    • multiple and single yaml parser
    • multiple and single xml parser
    • readme and changelog
    • logs

    i prepare pubspec to easy locale 2.2.0, if need test change to 2.2.0-dev

    opened by Overman775 1
  • HttpAssetLoader() not supported

    HttpAssetLoader() not supported

    Hi, I am try to call assetLoader: HttpAssetLoader() but HttpAssetLoader() is undefined. I added easy_localization and easy_localization_loader in ymal but still not reading. Need your response. Thank you

    opened by AnmolShahid 0
  • new parsers

    new parsers

    • multiple and single yaml parser
    • multiple and single xml parser
    • readme and changelog
    • logs

    i prepare pubspec to easy locale 2.2.0, if need test change to 2.2.0-dev

    opened by Overman775 0
  • extend autodetect

    extend autodetect

    I started to get errors with the last update due to auto detection of csv settings. I use ; as fieldDelimiter and as textDelimiter. Either these should be added or the library should be extendable.

    opened by deadsoul44 0
  • xml dependency incompatibility

    xml dependency incompatibility

    auto_router depends on xml 6.0.1 while this package depends on 5.0.2, which causes incompatibility with xml dependency. Please, upgrade your xml dependency.

    opened by erayerdin 3
  • http-local-asset translation loader

    http-local-asset translation loader

    if you are in need of a particular type of requirement such as:

    your translations in the asset are not complete so you want to use the remote translations but want to make them available for offline use. this makes the app useable if there is no internet connection to fetch the new translations every time.

    if there is translation file locally(cached) then

    1. merge the local translation file with the asset-bundler translation file but give priority to the local translation.
    2. if the local localization is older than [one day] then fetch the new localization from backend and save in local(cache) and perform 1st step.
    opened by stha-ums 0
Flutter custom utils

Get the MediaQuery size getSize(context) Make a responsive gridview by using bot

The Essential Utilities 0 Feb 23, 2022
Dart's native integers in custom bitwidth integer format

Dart's native integers in custom bit-width formats like i2, i4, i8, i16, i32, ix and u1, u2, u4, u8, u16, u32, ux...

Aldrin's Art Factory 2 Oct 30, 2022
An assets picker in WeChat style, support multi assets picking.

An assets picker in WeChat style, support multi assets picking.

FlutterCandies 1.1k Dec 30, 2022
An assets picker in WeChat style, support multi assets picking.

An assets picker in WeChat style, support multi assets picking.

FlutterCandies 1.1k Jan 8, 2023
A Flutter plugin that provides assets abstraction management APIs without UI integration, you can get assets (image/video/audio) on Android, iOS and macOS.

photo_manager Photo/Assets management APIs for Flutter without UI integration, you can get assets (image/video/audio) from Android, iOS and macOS. 提供相

FlutterCandies 526 Jan 4, 2023
Spider - A small dart library to generate Assets dart code from assets folder.

Spider A small dart library to generate Assets dart code from assets folder. It generates dart class with static const variables in it which can be us

Birju Vachhani 159 Nov 8, 2022
A collection of Login Screens, Buttons, Loaders and Widgets with attractive UIs built with Flutter

Flutter Screens A collection of Login Screens, Buttons, Loaders and Widgets with attractive UIs, built with Flutter, ready to be used in your applicat

Pham Quoc Duy 2 Dec 20, 2022
Play simultaneously music/audio from assets/network/file directly from Flutter, compatible with android / ios / web / macos, displays notifications

?? assets_audio_player ?? Play music/audio stored in assets files (simultaneously) directly from Flutter (android / ios / web / macos). You can also u

Florent CHAMPIGNY 651 Dec 24, 2022
The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs.

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs. Inspired by SwiftGen. Motivation Using asset path str

FlutterGen 1.1k Jan 6, 2023
It is too hard to balance money across different assets and accounts.

Cash Balancer It is too hard to balance money across different assets and accounts. Spreadsheets are too hostile; banks are too complex. This app shou

Bernardo Ferrari 75 Jan 1, 2023
This project include all the assets I used in this tutorial

clothes_app_starter A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you star

Ruize Nie 11 Jun 29, 2022
It is too hard to balance money across different assets and accounts.

Cash Balancer It is too hard to balance money across different assets and accounts. Spreadsheets are too hostile; banks are too complex. This app shou

Bernardo Ferrari 74 Dec 14, 2022
Loading indicator GIFs. Material and Cupertino (Android and iOS) loading indicators in assorted sizes. Use as placeholders for loading remote image assets. Demo: https://gallery.codelessly.com/flutterwebsites/loadinggifs/

Loading GIFs High quality Android and iOS loading spinners. View Demo Loading GIFs is a collection of high fidelity loading animations in GIF format.

Codelessly 31 Dec 23, 2022
Collection of common localization assets for Nations package

Nations Assets ?? collection of common localization assets for Nations package. FAQ Why not with Nations ? to make the Nations smaller and give the us

FlutterQueen 2 Jun 22, 2022
Flutter library to open JSON from assets.

jsonloader JSON Loader Package to read JSON from asset. Features Load and read JSON from assets. Getting Started In the pubspec.yaml of your flutter p

Yudi Setiawan 4 Nov 3, 2021
A Video and Audio player that can play from local assets, local files and network URLs with the powerful controls

Video/Audio Player in Flutter with Powerful controls How can we play videos in Flutter? There is a library directly from the Flutter team simply calle

Harsh Mistry 12 Jan 31, 2022
A day night time picker for Flutter. Beautiful day and night animation with Sun and Moon assets.

DayNightTimePicker A day night time picker for Flutter with Zero Dependencies. Default style: IOS style: View it on pub.dev Installation Add to pubspe

Subhamay Dutta 68 Dec 29, 2022
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

null 8.3k Dec 31, 2022
Asset manager helps you auto-generate the assets code and add it to your pubspec.yaml .

Asset Manager Asset manager helps you auto-generate the assets code and add it to your pubspec.yaml . Quick start dart pub global activate asset_manag

Rutvik Tak 9 Nov 1, 2022
best flutter / dart practices + Custom Painter + Sliver App Bar + Custom Scrollview

Weekly Budget Flutter App A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get yo

Mohamed Awnallah 4 Oct 21, 2021