installPackages method

Future<void> installPackages(
  1. String packageName,
  2. String project
)

Implementation

Future<void> installPackages(String packageName, String project) async {
  final url = Uri.parse('https://pub.dev/api/packages/$packageName');

  try {
    var response = await http.get(url);

    if (response.statusCode == HttpStatus.notFound) {
      print(jsonDecode(response.body)['message']);
      exit(1);
    } else {
      // Fetch the version
      var version = jsonDecode(response.body)['latest']['version'];

      //load the pubspec file
      final pubspec = File('$project/pubspec.yaml').readAsStringSync();

      final updatedPubspec = pubspec.replaceFirst(
          'dependencies:', 'dependencies:\n  $packageName: ^$version');

      File('$project/pubspec.yaml').writeAsStringSync(updatedPubspec);
    }
  } on HttpException catch (e) {
    print(e.message);
    exit(1);
  }
}