addModulePackages static method

void addModulePackages(
  1. List<String> deps,
  2. List<String> devDeps, {
  3. required bool runPubGet,
})

Adds the given runtime/dev packages to pubspec.yaml.

When Flutter is on PATH and runPubGet is true, uses flutter pub add so pub resolves versions compatible with the project's SDK (and runs an implicit pub get). Otherwise inserts unversioned entries into the appropriate pubspec sections.

Implementation

static void addModulePackages(
  List<String> deps,
  List<String> devDeps, {
  required bool runPubGet,
}) {
  final pubspec = File('pubspec.yaml');
  if (!pubspec.existsSync()) return;

  final existing = _existingTopLevelDeps(pubspec.readAsStringSync());
  final newDeps = deps.toSet().where((p) => !existing.contains(p)).toList()
    ..sort();
  final newDevDeps =
      devDeps.toSet().where((p) => !existing.contains(p)).toList()..sort();

  if (newDeps.isEmpty && newDevDeps.isEmpty) {
    print('All required packages are already present in pubspec.yaml.');
    return;
  }

  final flutterAvailable = isFlutterAvailable();

  if (runPubGet && flutterAvailable) {
    if (newDeps.isNotEmpty) {
      print('Adding packages: ${newDeps.join(', ')}');
      _runPubAdd(newDeps);
    }
    if (newDevDeps.isNotEmpty) {
      print('Adding dev packages: ${newDevDeps.join(', ')}');
      _runPubAdd(newDevDeps.map((d) => 'dev:$d').toList());
    }
    return;
  }

  _insertBareEntries(pubspec, newDeps, newDevDeps);
  if (!flutterAvailable) {
    print('Flutter not found on PATH — added unversioned entries to '
        'pubspec.yaml. Run "flutter pub get" to resolve versions.');
  } else {
    print('Added unversioned entries to pubspec.yaml (--no-pub-get set).');
  }
}