You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
samples/rolodex/lib/data/contact_group.dart

119 lines
2.9 KiB

// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:collection';
import 'package:flutter/cupertino.dart';
import 'contact.dart';
void _sortContacts(List<Contact> contacts) {
contacts.sort((Contact a, Contact b) {
final int checkLastName = a.lastName.compareTo(b.lastName);
if (checkLastName != 0) {
return checkLastName;
}
final int checkFirstName = a.firstName.compareTo(b.firstName);
if (checkFirstName != 0) {
return checkFirstName;
}
if (a.middleName != null && b.middleName != null) {
final int checkMiddleName = a.middleName!.compareTo(b.middleName!);
if (checkMiddleName != 0) {
return checkMiddleName;
}
} else if (a.middleName != null || b.middleName != null) {
return a.middleName != null ? 1 : -1;
}
// If both contacts have the exact same name, order by first created.
return a.id.compareTo(b.id);
});
}
typedef AlphabetizedContactMap = SplayTreeMap<String, List<Contact>>;
class ContactGroup {
factory ContactGroup({
required int id,
required String label,
bool permanent = false,
String? title,
List<Contact>? contacts,
}) {
final contactsCopy = contacts ?? <Contact>[];
_sortContacts(contactsCopy);
return ContactGroup._internal(
id: id,
label: label,
permanent: permanent,
title: title,
contacts: contactsCopy,
);
}
ContactGroup._internal({
required this.id,
required this.label,
this.permanent = false,
String? title,
List<Contact>? contacts,
}) : title = title ?? label,
_contacts = contacts ?? const <Contact>[];
final int id;
final bool permanent;
final String label;
final String title;
final List<Contact> _contacts;
List<Contact> get contacts => _contacts;
AlphabetizedContactMap get alphabetizedContacts {
final AlphabetizedContactMap contactsMap = AlphabetizedContactMap();
for (Contact contact in _contacts) {
final String lastInitial = contact.lastName[0].toUpperCase();
if (contactsMap.containsKey(lastInitial)) {
contactsMap[lastInitial]!.add(contact);
} else {
contactsMap[lastInitial] = [contact];
}
}
return contactsMap;
}
}
class ContactGroupsModel extends ChangeNotifier {
final List<ContactGroup> _lists = generateSeedData();
List<ContactGroup> get lists => _lists;
ContactGroup findContactList(int id) {
return lists[id];
}
}
final allPhone = ContactGroup(
id: 0,
permanent: true,
label: 'All iPhone',
title: 'iPhone',
contacts: allContacts.toList(),
);
final friends = ContactGroup(
id: 1,
label: 'Friends',
contacts: [allContacts.elementAt(3)],
);
final work = ContactGroup(id: 2, label: 'Work');
List<ContactGroup> generateSeedData() {
return [allPhone, friends, work];
}