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