Flutter:contact_services没有提供联系电话

时间:2020-03-22 06:50:14

标签: flutter flutter-dependencies

我正在使用 contact_services flutter插件从移动电话簿中获取联系人。

现在,我只需要联系人的姓名和电话号码。我已成功获取名称,但 对于电话号码,它正在终端中打印('item')的实例

我该怎么办?

电话簿类代码

import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';

class PhoneBook extends StatefulWidget {
  @override
  _PhoneBookState createState() => _PhoneBookState();
}

class _PhoneBookState extends State<PhoneBook> {
  List<Contact> _contacts;

  @override
  initState() {
    super.initState();
    refreshContacts();
  }

  Future<PermissionStatus> _getContactPermission() async {
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.contacts);
    if (permission != PermissionStatus.granted &&
        permission != PermissionStatus.granted) {
      Map<PermissionGroup, PermissionStatus> permissionStatus =
          await PermissionHandler()
              .requestPermissions([PermissionGroup.contacts]);
      return permissionStatus[PermissionGroup.contacts] ??
          PermissionStatus.unknown;
    } else {
      return permission;
    }
  }

  refreshContacts() async {
    PermissionStatus permissionStatus = await _getContactPermission();
    if (permissionStatus == PermissionStatus.granted) {
      // Load without thumbnails initially.
      var contacts =
          (await ContactsService.getContacts(withThumbnails: false)).toList();
//      var contacts = (await ContactsService.getContactsForPhone("8554964652"))
//          .toList();
      setState(() {
        _contacts = contacts;
      });

      // Lazy load thumbnails after rendering initial contacts.
      for (final contact in contacts) {
        ContactsService.getAvatar(contact).then((avatar) {
          if (avatar == null) return; // Don't redraw if no change.
          setState(() => contact.avatar = avatar);
        });
      }
    } else {
      _handleInvalidPermissions(permissionStatus);
    }
  }

  updateContact() async {
    Contact ninja = _contacts
        .toList()
        .firstWhere((contact) => contact.familyName.startsWith("Saifu"));
    ninja.avatar = null;
    await ContactsService.updateContact(ninja);

    refreshContacts();
  }

  void _handleInvalidPermissions(PermissionStatus permissionStatus) {
    if (permissionStatus == PermissionStatus.denied) {
      throw new PlatformException(
          code: "PERMISSION_DENIED",
          message: "Access to location data denied",
          details: null);
    } else if (permissionStatus == PermissionStatus.denied) {
      throw new PlatformException(
          code: "PERMISSION_DISABLED",
          message: "Location data is not available on device",
          details: null);
    }
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    return Scaffold(
      appBar: AppBar(title: Text('Phone Book'),),
      body: _contacts != null
          ? Container(
              height: height,
              width: width,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                    Color(0xff0D2C4F),
                    Color(0xff0D2C4F),
                    Color(0xff1D2631),
                    Color(0xff1D2631),
                  ])),
              child: SafeArea(
                child: ListView.separated(
                  separatorBuilder: (context, index) {
                    return Divider(
                      height: height * 0.01,
                      color: Colors.white54,
                    );
                  },
                  itemCount: _contacts?.length ?? 0,
                  itemBuilder: (BuildContext context, int index) {
                    Contact c = _contacts?.elementAt(index);
                    return ListTile(
                      trailing: FlatButton(
                        shape: CircleBorder(),
                        color: Colors.red,
                        onPressed: (){
                          print(c.phones);
                        },
                        child: Icon(Icons.add, size: height * 0.025, color: Colors.white,),
                      ),
                      leading: CircleAvatar(
                        child: Text('${c.displayName[0]}'),
                        radius: 15,
                      ),
                      title: Text(
                        c.displayName ?? "",
                        style: TextStyle(color: Colors.white),
                      ),
                    );
                  },
                ),
              ),
            )
          : Center(
              child: CircularProgressIndicator(
                valueColor: new AlwaysStoppedAnimation<Color>(Color(0xff1D2631)),
              ),
            ),
    );
  }
}

在属性 onPressed 中:(){我打印了电话号码}

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:4)

这是我的代码:

Future<void> getContacts (BuildContext context) async {
    Iterable<Contact> contacts = await ContactsService.getContacts();
        var iter = 0;

        contacts.forEach((contact) async {
          var mobilenum = contact.phones.toList();

          if (mobilenum.length != 0) {
            var userContact = UserContactItem(
                contactName: contact.displayName,
                number: mobilenum[0],
                imageUrl: contact.avatar);
            _userList.add(userContact);
            iter++;
          } else {
            iter++;
          }
     }
}

列表视图构建器中的实现

ListView.builder(
    itemCount: _userList.length,
    physics: NeverScrollableScrollPhysics(),
    shrinkWrap: true,
    itemBuilder: (context, contactIndex) {
        return ListTile(
           leading: !_userList[contactIndex].imageUrl.isEmpty
              ? CircleAvatar(
                   backgroundImage:MemoryImage(_userList[contactIndex].imageUrl),
              )
              : CircleAvatar(
                   child: Icon(Icons.add),
              ),
           onTap: () {
              print(_userList[contactIndex].contactName);
           },
           title: Text(_userList[contactIndex].contactName),
           subtitle: Text(_userList[contactIndex].number),
        );
    },
)

您可以在“ listTiles”内部实现“ onTap”,如下所示:

onTap: () {
   print(_userList[contactIndex].contactName);
},

这对我有用:)

答案 1 :(得分:1)

要获取电话号码,您只需要使用以下逻辑

var _numbers = _contactItem.contact.phones.toList();

然后打印,_numbers[0].value将为您打印电话号码。

如果您try _numbers[0].toString()将打印“项目实例”。

答案 2 :(得分:0)

这是电话号码的模型:

Iterable<Item> phones = [];

要访问可迭代数组中的项,您可以; 1)循环打印它们 2)或在可迭代数组中获取特定项。 ${iterable.first.toString()}->这将以字符串形式返回数组中的第一项。

您可以在https://dart.dev/codelabs/iterables上了解有关可迭代数组的更多信息。

希望这会有所帮助!