MeCard.fromPlainText constructor
Constructor from the plain text of the MeCard.
It is important to respect the format of the MeCard
.
The MeCard
format starts with the tag "MECARD:" and ends with a colon (";;").
For versions higher than 1.0, ending with 2 semicolons is not mandatory.
It is checked by default.
Set checkSemicolons
to false
to skip this check.
Implementation
factory MeCard.fromPlainText(String plainText, {bool checkSemicolons = true}) {
String text = plainText.replaceAll('\n', '');
if (!text.startsWith('MECARD:')) {
throw MeCardParsingError('MeCard must start with "MECARD:"');
}
if (checkSemicolons && !text.endsWith(';;')) {
throw MeCardParsingError('MeCard must end with ";;".');
}
text = text.substring(7, text.length - 2).trim();
final texts = text.split(';');
String name = '';
String? lastName;
String? nickname;
String? organization;
String? role;
List<String> telephones = [];
List<String> videophones = [];
List<String> emails = [];
List<String> addresses = [];
List<String> urls = [];
DateTime? birthday;
List<MeCardSocialProfile> socialProfiles = [];
String? note;
for (int i = 0; i < texts.length; i++) {
final t = texts[i];
if (t.contains('N:')) {
final temp = t.substring(2).split(',');
name = temp[1].trim();
if (name.isEmpty) {
throw MeCardParsingError('The "N" field, for "name", is mandatory.');
}
if (temp[0].trim().isNotEmpty) {
lastName = temp[0].trim();
}
} else if (t.contains('NICKNAME:')) {
nickname = t.substring(9).trim();
} else if (t.contains('ORG:')) {
organization = t.substring(4).trim();
} else if (t.contains('TITLE:')) {
role = t.substring(6).trim();
} else if (t.contains('TEL:')) {
telephones.add(t.substring(4).trim());
} else if (t.contains('TEL-AV:')) {
videophones.add(t.substring(7).trim());
} else if (t.contains('EMAIL:')) {
emails.add(t.substring(6).trim());
} else if (t.contains('ADR:')) {
addresses.add(t.substring(4).trim());
} else if (t.contains('URL:')) {
urls.add(t.substring(4).trim());
} else if (t.contains('BDAY:')) {
birthday = DateTime.tryParse(t.substring(5).trim());
} else if (t.contains('X-SOCIALPROFILE')) {
i++;
final tt = texts[i].replaceFirst(':', ';').split(';');
socialProfiles.add(MeCardSocialProfile(
type: tt.first.trim().substring(5),
url: tt[1],
));
} else if (t.contains('NOTE:')) {
note = t.substring(5);
}
}
return MeCard(
name: name,
lastName: lastName,
nickname: nickname,
organization: organization,
role: role,
telephones: telephones,
videophones: videophones,
emails: emails,
addresses: addresses,
urls: urls,
birthday: birthday,
socialProfiles: socialProfiles,
note: note,
);
}