Flutter联系人选择器

时间:2020-03-06 14:23:46

标签: flutter

我在flutter应用程序中使用contact_picker来访问从手机通讯录中获取联系人。当我单击电话簿中的联系人姓名时,该应用程序崩溃。

这是代码:

import 'package:flutter/material.dart';
import 'package:contact_picker/contact_picker.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final ContactPicker _contactPicker = new ContactPicker();
  Contact _contact;

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Plugin example app'),
        ),
        body: new Center(
          child: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new MaterialButton(
                color: Colors.blue,
                child: new Text("CLICK ME"),
                onPressed: () async {
                  Contact contact = await _contactPicker.selectContact();
                  setState(() {
                    _contact = contact;
                  });
                },
              ),
              new Text(
                _contact == null ? 'No contact selected.' : _contact.toString(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

以下是显示的错误:

D/AndroidRuntime(14310): Shutting down VM
E/AndroidRuntime(14310): FATAL EXCEPTION: main
E/AndroidRuntime(14310): Process: com.example.kubera_sample, PID: 14310
E/AndroidRuntime(14310): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2015, result=-1, data=Intent { dat=content://com.android.contacts/data/3 flg=0x1 }} to activity {com.example.kubera_sample/com.example.kubera_sample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.app.Activity.getContentResolver()' on a null object reference
E/AndroidRuntime(14310):    at android.app.ActivityThread.deliverResults(ActivityThread.java:4360)
E/AndroidRuntime(14310):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4402)
E/AndroidRuntime(14310):    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
E/AndroidRuntime(14310):    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
E/AndroidRuntime(14310):    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
E/AndroidRuntime(14310):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
E/AndroidRuntime(14310):    at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(14310):    at android.os.Looper.loop(Looper.java:193)
E/AndroidRuntime(14310):    at android.app.ActivityThread.main(ActivityThread.java:6669)
E/AndroidRuntime(14310):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(14310):    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/AndroidRuntime(14310):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/AndroidRuntime(14310): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.app.Activity.getContentResolver()' on a null object reference
E/AndroidRuntime(14310):    at net.goderbauer.flutter.contactpicker.ContactPickerPlugin.onActivityResult(ContactPickerPlugin.java:68)
E/AndroidRuntime(14310):    at io.flutter.embedding.engine.FlutterEnginePluginRegistry$FlutterEngineActivityPluginBinding.onActivityResult(FlutterEnginePluginRegistry.java:634)
E/AndroidRuntime(14310):    at io.flutter.embedding.engine.FlutterEnginePluginRegistry.onActivityResult(FlutterEnginePluginRegistry.java:367)
E/AndroidRuntime(14310):    at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onActivityResult(FlutterActivityAndFragmentDelegate.java:546)
E/AndroidRuntime(14310):    at io.flutter.embedding.android.FlutterActivity.onActivityResult(FlutterActivity.java:594)
E/AndroidRuntime(14310):    at android.app.Activity.dispatchActivityResult(Activity.java:7454)
E/AndroidRuntime(14310):    at android.app.ActivityThread.deliverResults(ActivityThread.java:4353)
E/AndroidRuntime(14310):    ... 11 more
I/Process (14310): Sending signal. PID: 14310 SIG: 9
Lost connection to device

知道为什么会这样吗? 我正在使用contact_picker 0.0.2

电话簿出现,但单击联系人后,应用程序崩溃。

1 个答案:

答案 0 :(得分:2)

您需要编辑以下文件 C:\您的发布缓存目录\ contact_picker-0.0.1 + 2 \ android \ src \ main \ java \ net \ goderbauer \ flutter \ contactpicker \ ContactPickerPlugin.java < / strong>,并替换为以下代码。



    // Copyright 2017 Michael Goderbauer. All rights reserved.
    // Use of this source code is governed by a BSD-style license that can be
    // found in the LICENSE file.

    package net.goderbauer.flutter.contactpicker;

    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.net.Uri;
    import android.provider.ContactsContract;

    import java.util.HashMap;

    import io.flutter.plugin.common.MethodChannel;
    import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
    import io.flutter.plugin.common.MethodChannel.Result;
    import io.flutter.plugin.common.MethodCall;
    import io.flutter.plugin.common.PluginRegistry;
    import io.flutter.plugin.common.PluginRegistry.Registrar;

    import static android.app.Activity.RESULT_OK;

    public class ContactPickerPlugin implements MethodCallHandler, PluginRegistry.ActivityResultListener {
      public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), "contact_picker");
        ContactPickerPlugin instance = new ContactPickerPlugin(registrar.activity());
        registrar.addActivityResultListener(instance);
        channel.setMethodCallHandler(instance);
      }

        private ContactPickerPlugin(Activity activity) {
            this.activity = activity;
        }

      private static int PICK_CONTACT = 2015;

      private Activity activity;
      private Result pendingResult = null;

      @Override
      public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals("selectContact")) {
          if (pendingResult != null) {
            pendingResult.error("multiple_requests", "Cancelled by a second request.", null);
            pendingResult = null;
          }
          pendingResult = result;

          Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
          activity.startActivityForResult(i, PICK_CONTACT);
        } else {
          //result.notImplemented();
         pendingResult = null;
        }
      }

      @Override
      public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != PICK_CONTACT) {
          return false;
        }
        if (resultCode != RESULT_OK) {
          pendingResult.success(null);
          pendingResult = null;
        }
        if(pendingResult != null){
        Uri contactUri = data.getData();
        Cursor cursor = activity.getContentResolver().query(contactUri, null, null, null, null);
        cursor.moveToFirst();

        int phoneType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
        String customLabel = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
        String label = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(activity.getResources(), phoneType, customLabel);
        String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        String fullName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

        HashMap phoneNumber = new HashMap();
        phoneNumber.put("number", number);
        phoneNumber.put("label", label);

        HashMap contact = new HashMap();
        contact.put("fullName", fullName);
        contact.put("phoneNumber", phoneNumber);

        pendingResult.success(contact);
        pendingResult = null;
        return true;
      }
      else{
        pendingResult = null;
        return false;
      }
      }
    }

干杯!