addAssetToPubspec static method

Future<void> addAssetToPubspec(
  1. String assetPath
)



Implementation

static Future<void> addAssetToPubspec(String assetPath) async {
  final pubspec = File('pubspec.yaml');

  if (!await pubspec.exists()) {
    print('❌ pubspec.yaml not found!');
    return;
  }

  List<String> lines = await pubspec.readAsLines();

  bool isAlreadyAdded = lines.any(
    (line) => line.trim().contains('- $assetPath'),
  );
  if (isAlreadyAdded) {
    print('⚠️ Asset "$assetPath" is already in pubspec.yaml');
    return;
  }

  int flutterIndex = lines.lastIndexWhere(
    (line) => line.trim() == 'flutter:',
  );

  if (flutterIndex != -1) {
    int assetsIndex = -1;

    for (int i = flutterIndex + 1; i < lines.length; i++) {
      final line = lines[i];

      if (line.trim().isNotEmpty && !line.startsWith('  ')) break;

      if (line.trim() == 'assets:') {
        assetsIndex = i;
        break;
      }
    }

    if (assetsIndex != -1) {
      lines.insert(assetsIndex + 1, '    - $assetPath');
      print(
        '➕ Added "$assetPath" to existing assets list (in last flutter block).',
      );
    } else {
      lines.insertAll(flutterIndex + 1, ['  assets:', '    - $assetPath']);
      print(
        '🆕 Created assets section in last flutter block and added "$assetPath".',
      );
    }

    // حفظ التعديلات
    await pubspec.writeAsString(lines.join('\n'));
  } else {
    print('❌ "flutter:" section not found in pubspec.yaml');
  }
}