add_person.dart 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import 'dart:io';
  2. import 'dart_tutorial/addressbook.pb.dart';
  3. /// This function fills in a Person message based on user input.
  4. Person promptForAddress() {
  5. final person = Person();
  6. print('Enter person ID: ');
  7. final input = stdin.readLineSync();
  8. person.id = int.parse(input);
  9. print('Enter name');
  10. person.name = stdin.readLineSync();
  11. print('Enter email address (blank for none) : ');
  12. final email = stdin.readLineSync();
  13. if (email.isNotEmpty) person.email = email;
  14. while (true) {
  15. print('Enter a phone number (or leave blank to finish): ');
  16. final number = stdin.readLineSync();
  17. if (number.isEmpty) break;
  18. final phoneNumber = Person_PhoneNumber()..number = number;
  19. print('Is this a mobile, home, or work phone? ');
  20. final type = stdin.readLineSync();
  21. switch (type) {
  22. case 'mobile':
  23. phoneNumber.type = Person_PhoneType.MOBILE;
  24. break;
  25. case 'home':
  26. phoneNumber.type = Person_PhoneType.HOME;
  27. break;
  28. case 'work':
  29. phoneNumber.type = Person_PhoneType.WORK;
  30. break;
  31. default:
  32. print('Unknown phone type. Using default.');
  33. }
  34. person.phones.add(phoneNumber);
  35. }
  36. return person;
  37. }
  38. /// Reads the entire address book from a file, adds one person based
  39. /// on user input, then writes it back out to the same file.
  40. void main(List<String> arguments) {
  41. if (arguments.length != 1) {
  42. print('Usage: add_person ADDRESS_BOOK_FILE');
  43. exit(-1);
  44. }
  45. final file = File(arguments.first);
  46. AddressBook addressBook;
  47. if (!file.existsSync()) {
  48. print('File not found. Creating new file.');
  49. addressBook = AddressBook();
  50. } else {
  51. addressBook = AddressBook.fromBuffer(file.readAsBytesSync());
  52. }
  53. addressBook.people.add(promptForAddress());
  54. file.writeAsBytes(addressBook.writeToBuffer());
  55. }