flutter_gen icon indicating copy to clipboard operation
flutter_gen copied to clipboard

Can support custom integration?

Open jiajiawei opened this issue 2 years ago • 1 comments

image At first I used this method: 'page.login.userName'.tr. I want to change it to the following I thought fluttergen could do this, but it does not support custom generation

jiajiawei avatar Jun 09 '22 12:06 jiajiawei

That's what I want to do too.

wasabeef avatar Jun 14 '22 07:06 wasabeef

Refer to the source code, and I implemented it myself It is also configured to the task in the vscode for execution

The code is as follows. package:i18ngen/string_ext.dart is packages/core/lib/utils/string.dart

import 'dart:io';

import 'package:dart_style/dart_style.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'package:i18ngen/string_ext.dart';

void main(List<String> arguments) {
  final dir = path.dirname(Platform.script.path).substring(1);
  final yamlFile = path.join(dir, '../../../assets/i18n/zh_CN.yaml');
  final content = File(yamlFile).readAsStringSync();
  final YamlMap map = loadYaml(content);
  final sb1 = StringBuffer();
  final sb2 = StringBuffer();
  final sb3 = StringBuffer();
  for (final k1 in map.keys) {
    final className = '\$${k1.toString().upCamelCase()}Gen';
    sb1.writeln('final $k1 = $className();');
    final v1 = map[k1];
    sb2.writeln('class $className{');
    for (final k2 in v1.keys) {
      final v2 = v1[k2];
      if (v2 is String) {
        sb2.writeln("String $k2 = '$k1.$k2';");
      } else if (v2 is YamlMap) {
        final className2 =
            '\$${k1.toString().upCamelCase()}${k2.toString().upCamelCase()}Gen';
        sb2.writeln('final $k2 = $className2();');
        sb3.writeln('class $className2{');
        for (final k3 in v2.keys) {
          sb3.writeln("String $k3 = '$k1.$k2.$k3';");
        }
        sb3.writeln('}');
      }
    }
    sb2.writeln('}');
  }
  final sb = StringBuffer(
      '''
// ignore_for_file: non_constant_identifier_names
Translation t = Translation();
class Translation {
  $sb1
}
$sb2
$sb3
''');
  final code = DartFormatter().format(sb.toString());
  final codePath = path.join(dir, '../../../lib/common/gen/translation.dart');
  final codeFile = File(codePath);
  if (codeFile.existsSync()) codeFile.deleteSync();
  codeFile.writeAsStringSync(code);
}

jiajiawei avatar Oct 25 '22 01:10 jiajiawei