Search code examples
dartcommand-line-interfaceargs

How to get a number as a cli argument?


I have this code

import 'dart:io';
import 'package:args/args.dart';

void main(List<String> args) {
  var p = ArgParser();
  p.addOption('number', abbr: 'n');
  var results = p.parse(args);
}

For the option number, I want to restrict only ints to be entered and if there isn't any, a error will be given. Is there something I can do for that to happen?


Solution

  • The package does not do validation for you, here is some code I wrote for an option called minLength:

    var minLength = argResults!['minLength'];
    if (minLength != null) {
      if (int.tryParse(minLength) == null || int.parse(minLength) < 1) {
        print('--minLength value must be a positive integer.');
        exit(64);
      }
    }