Giter Club home page Giter Club logo

r_flutter's Introduction

r_flutter

Generate constants for resources which require using them as a String like fonts and assets. Generated file will look like this: assets.dart

Setup

  1. Add dependencies in your pubspec.yaml:
dependencies:
  flutter:
    sdk: flutter

dev_dependencies:
  build_runner:
  r_flutter: <version>
  1. Add r_flutter configuration in your pubspec.yaml:
# important: this is root level option
r_flutter:
  intl: lib/i18n/en.arb
  add_file_path_comments: false # default is true
  ignore:
    - lib/assets/sub/ignore1 #use ignore option to skip 
    - lib/assets/sub/ignore2
    - lib/i18n

Options:

  • intl: Points to a localization file that would be used to generate localization keys. arb files are essentialy json files with some special, optional keys. Specifing this is optional.
  • add_file_path_comments: specifies wither it should print file paths comments for assets files.
  • ignore: specifies a list of files/directories that should be skipped during code generation.
  1. Execute flutter packages pub run build_runner build command in your project's directory. Alternativly you can run flutter pub run r_flutter:generate to only run r_flutter without using the whole build_runner. assets.dart will be generated into lib/assets.dart

  2. Import assets.dart and start using it:

import 'assets.dart'
Image(image: Images.image)

Note: if something doesn't work, check the example project.

I18n

  1. Add default localization file to pubspec.yaml
r_flutter:
  intl: lib/i18n/en.arb

Other locales will be searched under the same folder as the default localization file (e.g. lib/i18n/) for the following 4 formats:

  • <language_code>.arb (e.g.: en.arb, zh.arb)
  • <language_code>_<country_code>.arb (e.g.: en_US.arb, en_GB.arb)
  • <language_code>_<script_code>.arb (e.g.: zh_Hans.arb, zh_Hant.arb)
  • <language_code>_<script_code>_<country_code>.arb (e.g.: zh_Hans_CN.arb, zh_Hant_TW.arb, zh_Hant_HK.arb)

Where <language_code> consists of 2 lowercase letters (ISO 639-1); <country_code> consists of 2 uppercase letters (ISO_3166-2); <script_code> consists of 4 letters with the first letter being capitalized (ISO 15924).

  1. Add it to your app.
MaterialApp(
  title: 'r_flutter',
  supportedLocales: I18n.supportedLocales,
  localizationsDelegates: [
    I18n.delegate
  ],
  home: HomePage(),
)
  1. Use it
import 'assets.dart'
Text(I18n.of(context).hello)

Organize I18n strings by feature

It is possible to organize i18n strings by feature so that they are not stored in one huge file.

  1. Add default localization file and feature definitions to pubspec.yaml
r_flutter:
  intl: lib/i18n/en.arb
  intl_features:
    - name: home
      path: lib/custom/path/to/home/
    - name: announcement
    - name: profile

If a path is not specified it is assumed to be a subdirectory of the main intl file directory. In this example the announcement and profile translation files will be placed under lib/i18n/announcement/ and lib/i18n/profile/ respectively.

  1. Create the actual translation files for the features and run the generator as usual.

  2. Use it

import 'assets.dart'
Text(I18n.of(context).home.hello)

Custom asset classes

r_flutter supports third party packages like flutter_svg by providing option to convert generated constants directly into the desired class. To use it, you need to configure which file extension should by handled by which class, for example:

r_flutter:
  asset_classes:
    ".svg": 
      import: asset_classes.dart
      class: SvgFile

And then, r_flutter will use SvgFile class for all svg assets:

static const SvgFile svg = SvgFile("lib/assets/svg.svg")

Troubleshooting

iOS won't show the correct language

The iOS project need to be updated: Documentation

Examples

Images

Instead of writing:

Image(image: AssetImage("assets/path/to/image.png"))

you can write:

Image(image: Images.image)
Fonts

Instead of writing:

TextStyle(
    fontFamily: "Roboto",
)

you can write:

TextStyle(
    fontFamily: Fonts.roboto,
)
Fonts

Instead of writing:

await rootBundle.loadString("assets/path/to/data.json")

you can write:

await rootBundle.loadString(Assets.data)

r_flutter's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

r_flutter's Issues

null-aware operation '!' runtime warning ๐Ÿคทโ€โ™€๏ธ

So I'm getting a lot of red from debug console with no real implications, e.g.:

i18n.dart:7241:46: Warning: Operand of null-aware operation '!' has type 'Map<String, String>' which excludes null.
 - 'Map' is from 'dart:core'.
            placeholders!["DepartureTime"]!, placeholders!["ArrivalTime"]!);

The thing is if I remove the 2nd ! in the generated code I'm getting then compilation error ๐Ÿคทโ€โ™€๏ธ

Problem with Flutter 1.17

Hello,

I updated my project to Flutter 1.17 stable and now the compiler can't find the assets.dart file.
The file itself is generated and I can see it exists at .dart_tool/build/generated/YOUR_PACKAGE_NAME/lib/assets.dart but the compiler fails with the following error:

Compiler message:
lib/main.dart:10:8: Error: Error when reading 'lib/assets.dart': No such file or directory
import 'package:XXX/assets.dart';

More resilient key escaping

Currently r_flutter is escaping keys that contain . We've come across a project that has also - and defined in the keys. It would be nice to fix those. PR attached

Conflict build process when used with `build_runner`

I was trying to do JSON parsing and the recommended way uses build_runner. But after build_runner ran, the asset.dart file is deleted.

Running flutter generate again will not regenerate asset.dart.

Currently just doing JSON parsing by hand instead of the recommended way but would be great if we can solve this.

Using code_builder for generating source code?

Hello.

I am working on adding a new feature to this package but while reading the code I saw that it uses just string buffers to generate the source code. It looks like this approach is quite fast.

I am wondering if there is any value in updating the generator to use something like code_builder. I can update it and open a PR if I know that this is something that is needed. Otherwise the current approach works just fine and does not cause any troubles AFAIK.

@timfreiheit what are your thoughts on this?

Input file format

Hi,
This looks pretty awesome. Can I only process arb files?
If would be awesome if we also could process simple cvs files as input for internationalisation.

Have you thought about this?
Cheers
Thomas

Add support for parameters and pluralizations

Currently if I define string like this:

"myKey": "{parameter, select, first{First} second{Second} other{Other}}",
"@myKey": {
  "description": "Description of usage",
  "placeholders": {
    "parameter": {
      "type": "String"
    }
  }
}

the generated localizations expect to receive three parameters (String First, String Second, String Other).
It would be great if we can use such feature as well.

Notes from lint - unnecessary_null_comparison

Generated piece:

I18nLookup _findLookUpFromLocale(Locale locale) {
  final String languageCode = locale != null ? locale.languageCode : "";
  switch (languageCode) {
    case "de":
      return I18nLookup_de();
  }
  return I18nLookup_de();
}

could be reduced to:

I18nLookup _findLookUpFromLocale(Locale locale) {
  switch (locale.languageCode) {
    case "de":
      return I18nLookup_de();
  }
  return I18nLookup_de();
}

Incompatible with build_runner 2.0

The new build_runner version (^2.0.0) depends on build_config > 1.0.0 and r_flutter ^0.7.1 requires build_config ^0.4.7.

This is very problematic because other packages can depend on build_runner 2.0.0, but I cannot update it because of r_flutter. Build_runner is a popular package that's also used in json serialization, freezed, mockito, etc.

To fix: update build_config dependency to >1.0.0.

Support assets localization

Hi!

It would be very nice to be able to localize assets in a similar way Android does, following a directory naming convention (drawable, drawable-nl etc).

Flutter already follows a similar strategy for different pixel ratios, so it could be combined with locale in a similar way.

What do you think?

Thanks for your work ๐Ÿ™‚

Avoid use of absolute paths in generated file

In the generated file I'll have something like:

/// ![](file:///Users/itsJoKr/Documents/projects/Flutter-Project/assets/svg/invoice_icon.svg)

When multiple people work on the same project these files will always have changes in them. Can I somehow remove this comment completely from generate because I would like to see clean git history?

[intl] Support for country code on i18n

Description

Currently, r_flutter does not support locales with country code or script code. For example, if we want to distinguish between zh_CN.arb (for China) and zh_HK.arb (for Hong Kong), the generation would fail with an exception.

// Full Chinese support for CN, TW, and HK
supportedLocales: [
  const Locale.fromSubtags(languageCode: 'zh'), // generic Chinese 'zh'
  const Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'), // 'zh_CN'
  const Locale.fromSubtags(languageCode: 'zh', countryCode: 'TW'), // 'zh_TW'
  const Locale.fromSubtags(languageCode: 'zh', countryCode: 'HK'), // 'zh_HK'
],

Proposal

Support {language_code}_{country_code}.arb file names instead of just {language_code}.arb.

For example:

  • zh_CN.arb for China, zh_HK.arb for Hong Kong, and zh_TW.arb for Taiwan.
  • en_US.arb for US English, and en_UK.arb for UK English.

Asset generation - improvements

I may do these soon:

  1. Ignore dot files.

This should not be in my assets class

static const String dSStore = "resources/images/.DS_Store";
  1. Document assets with images if possible.

Something like this: https://github.com/flutter/engine/blob/master/lib/ui/painting.dart#L417
I'm not sure if this can be done without absolute links. But if it worked, it would be super neat.

  1. Somehow support .svg and maybe other types.

I'm using svg assets mostly, which means I have to deal with strings:

static const String cancel = "resources/images/icons/cancel.svg";

Maybe it would be possible to improve generation somehow to have something like this:

static const String cancel = AssetSvg("resources/images/icons/cancel.svg");

so it's easier to enforce that given function expects path to svg file, add helper method into it, etc. Could be totally hardcoded for svg, or maybe some kind of template / config is needed to support other file types.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.