简体   繁体   English

在颤振/飞镖中添加电话号码以联系

[英]Adding phone number to contact in flutter/dart

I'm building a selectable checkbox contact list in flutter but if a contact has only an email and no number, an error is thrown.我正在 flutter 中构建一个可选择的复选框联系人列表,但如果联系人只有 email 并且没有号码,则会引发错误。 I want to create a loop to add a number of '99999' to the contacts phone number if they don't have one.如果联系人电话号码没有,我想创建一个循环以将数字“99999”添加到联系人电话号码中。 Please can someone guide me with an explanation of what I should change to make this work?请有人指导我解释我应该改变什么来完成这项工作? I have had a go, but I am quite new to flutter so I'm not completely certain on syntax etc...我有一个 go,但我对 flutter 很陌生,所以我对语法等并不完全确定......

Here is the part of the code that I am trying to put the function into.这是我试图将 function 放入的代码部分。

setMissingNo()async {
  Iterable<Contact> contactsToLoop = (await ContactsService.getContacts()).toList();
  contactsToLoop.forEach((Contact) { contactsToLoop = []..add(Item.fromMap({'label': 'work', 'value': 99999})); });
}

//fetch contacts from setMissingNo
  getAllContacts() async{
  Iterable<Contact> _contacts = (await ContactsService.getContacts()).toList(); 

setState(() {
  contacts = _contacts;
  }
  );
}

Here is my whole code这是我的整个代码

import 'package:flutter/material.dart';
// TODO: make it ask for permissions otherwise the app crashes
import 'package:contacts_service/contacts_service.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
List<Contact> contacts = [];
List<Contact> contactsFiltered = [];
TextEditingController searchController = new TextEditingController();

@override
  void initState() {
    super.initState();
    getAllContacts();
    searchController.addListener(() => filterContacts());
  }

//remove the +'s and spaces from a phone number before its searched
 String flattenPhoneNumber(String phoneStr) {
    return phoneStr.replaceAllMapped(RegExp(r'^(\+)|\D'), (Match m) {
      return m[0] == "+" ? "+" : "";
    });
  }


//loop and set all contacts without numbers to 99999, pass new list to getAllContacts
setMissingNo()async {
  Iterable<Contact> contactsToLoop = (await ContactsService.getContacts()).toList();
  contactsToLoop.forEach((Contact) { contactsToLoop = []..add(Item.fromMap({'label': 'work', 'value': 99999})); });
}

//fetch contacts from setMissingNo
  getAllContacts() async{
  Iterable<Contact> _contacts = (await ContactsService.getContacts()).toList(); 

setState(() {
  contacts = _contacts;
  }
  );
}


//filtering contacts function to match search term
 filterContacts() {
    List<Contact> _contacts = [];
    _contacts.addAll(contacts);
    if (searchController.text.isNotEmpty) {
      _contacts.retainWhere((contact) {
        String searchTerm = searchController.text.toLowerCase();
        String searchTermFlatten = flattenPhoneNumber(searchTerm);
        String contactName = contact.displayName.toLowerCase();
        bool nameMatches = contactName.contains(searchTerm);
        if (nameMatches == true) {
          return true;
        }

        if (searchTermFlatten.isEmpty) {
          return false;
        }

        var phone = contact.phones.firstWhere((phn) {
          String phnFlattened = flattenPhoneNumber(phn.value);
          return phnFlattened.contains(searchTermFlatten);
        }, orElse: () => null);

        return phone != null;
      });

      setState(() {
        contactsFiltered = _contacts;
      });
    }
  }



final selectedContacts = Set<Contact>();

  @override
  Widget build(BuildContext context) {
    bool isSearching = searchController.text.isNotEmpty;

    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[

            AppBar(
              title: Text('Create Group'),
            ),

            Container(
              child: TextField(
                controller: searchController,
                decoration: InputDecoration(
                  labelText: 'Search Contacts',
                  border: OutlineInputBorder(
                    borderSide: new BorderSide(
                      color: Theme.of(context).primaryColor
                    )
                  ),
                  prefixIcon: Icon(
                    Icons.search,
                    color: Theme.of(context).primaryColor
                  )
                ),
              ),
            ),

                 Expanded( child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: isSearching == true ? contactsFiltered.length : contacts.length,
                    itemBuilder: (context, index) {
                    Contact contact = isSearching == true ? contactsFiltered[index] : contacts[index];
                    //TODO: make it so when you clear your search, all items appear again & when you search words it works
                    return CheckboxListTile(
                      title: Text(contact.displayName),
                      subtitle: Text(
                        contact.phones.elementAt(0).value
                        ),                      
                       value: selectedContacts.contains(contact),
                  onChanged: (bool value) { 
                    if (value) { 
                      selectedContacts.add(contact); 
                    } else {
                      selectedContacts.remove(contact); 
                    }
                    setState((){}); 

                               // TODO: add in function to add contact ID to a list
                           });
                          },
                          ),

                    /*new Expanded(
                    child: Align(
                    alignment: Alignment.bottomLeft,
                     child: BottomNavigationBar(  
                currentIndex: _currentIndex,   

        items: const <BottomNavigationBarItem>[

//TODO: create new contact functionality to add someone by name + email
          BottomNavigationBarItem(
            icon: Icon(Icons.add),
            title: Text('Add Contact'),
          ),

          BottomNavigationBarItem(
            icon: Icon(Icons.create),
            title: Text('Create Group'),
          ),

        ],  
        onTap: (index) {
                  setState(() {
                  _currentIndex = index;
                  });     
                  }
        )
                    )
        )*/
        )
          ],
        )
      ),
    );
  }
}

Updating all contacts listed on the device might take a long time depending on the size of the device's contact list.更新设备上列出的所有联系人可能需要很长时间,具体取决于设备联系人列表的大小。 Add that the task is being done on the UI thread.添加该任务正在 UI 线程上完成。 You may want to consider using Isolate for the task to move away the load from the UI thread.您可能需要考虑对任务使用Isolate以减轻 UI 线程的负载。 If you can also provide the errors that you're getting, it'll help us get a picture of the issue.如果您还可以提供您遇到的错误,它将帮助我们了解问题。

Another thing is, the way you're approaching the issue might be impractical.另一件事是,您处理问题的方式可能不切实际。 Is it really necessary to write a placeholder phone number to the contacts?真的有必要给联系人写一个占位符电话号码吗? The issue likely stems from trying to fetch the number from a contact but the Object returns null.该问题可能源于尝试从联系人获取号码,但 Object 返回 null。 Perhaps you may want to consider only updating the phone number when the contact is selected.也许您可能只想在选择联系人时考虑更新电话号码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM