// 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 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>; class ContactGroup { factory ContactGroup({ required int id, required String label, bool permanent = false, String? title, List? contacts, }) { final contactsCopy = contacts ?? []; _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? contacts, }) : title = title ?? label, _contacts = contacts ?? const []; final int id; final bool permanent; final String label; final String title; final List _contacts; List 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 _lists = generateSeedData(); List 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 generateSeedData() { return [allPhone, friends, work]; }