简体   繁体   中英

How to change text in textformfield in flutter conatct picker

I have fluttercontactpicker as suffix in my textformfield.

while selecting the contact it is not showing in textformfield.

EditTextField(
                                onChanged: (text) {
                                  setState(() => _phn = text);
                                },
                                input: [FilteringTextInputFormatter.digitsOnly],
                                isPassword: false,
                                inputType: TextInputType.number,
                                decoration: country_code,
                                isSuffix: InkWell(
                                  onTap: () async {
                                    final PhoneContact contact =
                                        await FlutterContactPicker
                                            .pickPhoneContact();
                                    if (contact != null) {
                                      setState(() {
                                        _phn = contact.phoneNumber!.number
                                            .removeAllWhiteSpace()
                                            .replaceFirst('+91', '')
                                            .toString();
                                        print("this is $_phn");
                                      });
                                    }
                                  },
                                  child: const Icon(
                                    Icons.contacts,
                                    color: t5DarkNavy,
                                  ),
                                ),
                              ),

You need to make use of controller for TextForm Field here is an example, you can update controller text with setState

    import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:fluttercontactpicker/fluttercontactpicker.dart';

void main() => runApp(MyApp());

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) => MaterialApp(
    home: MainWidget(),
  );
}

class MainWidget extends StatefulWidget {
  @override
  _MainWidgetState createState() => _MainWidgetState();
}

class _MainWidgetState extends State<MainWidget> {
  PhoneContact? _phoneContact;
  EmailContact? _emailContact;
  String? _contact;
  Image? _contactPhoto;

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: const Text('Plugin example app'),
    ),
    body: Column(
      children: kIsWeb && !FlutterContactPicker.available
          ? [_buildError(context)]
          : _buildChildren(context),
    ),
  );

  Widget _buildError(BuildContext context) {
    return RichText(
      text: TextSpan(
          text:
          'Your browser does not support contact pickers for more information see: ',
          children: [
            TextSpan(
                text: 'https://web.dev/contact-picker/',
                style: TextStyle(
                  color: Colors.blue,
                  decoration: TextDecoration.underline,
                ),
                recognizer: TapGestureRecognizer()
                  ..onTap = () => launch('https://web.dev/contact-picker/')),
            TextSpan(text: ' and '),
            TextSpan(
                text:
                'https://developer.mozilla.org/en-US/docs/Web/API/Contact_Picker_API#Browser_compatibility/',
                style: TextStyle(
                  color: Colors.blue,
                  decoration: TextDecoration.underline,
                ),
                recognizer: TapGestureRecognizer()
                  ..onTap = () => launch(
                      'https://developer.mozilla.org/en-US/docs/Web/API/Contact_Picker_API#Browser_compatibility'))
          ]),
    );
  }

  List<Widget> _buildChildren(BuildContext context) {
    return <Widget>[
      if (_emailContact != null)
        Column(
          children: <Widget>[
            const Text("Email contact:"),
            Text("Name: ${_emailContact!.fullName}"),
            Text(
                "Email: ${_emailContact!.email!.email} (${_emailContact!.email!.label})")
          ],
        ),
      if (_phoneContact != null)
        Column(
          children: <Widget>[
            const Text("Phone contact:"),
            TextFormField(
              controller: TextEditingController()..text = '${_phoneContact!.fullName}',
              onSaved: (String? value) {
                debugPrint("Value Set To Be : ${_phoneContact!.fullName}");
              },
            ),
            Text(
                "Phone: ${_phoneContact!.phoneNumber!.number} (${_phoneContact!.phoneNumber!.label})")
          ],
        ),
      if (_contactPhoto != null) _contactPhoto!,
      if (_contact != null) Text(_contact!),
      ElevatedButton(
        child: const Text("pick phone contact"),
        onPressed: () async {
          final PhoneContact contact =
          await FlutterContactPicker.pickPhoneContact();
          print(contact);
          setState(() {
            _phoneContact = contact;
          });
        },
      ),
      ElevatedButton(
        child: const Text("pick email contact"),
        onPressed: () async {
          final EmailContact contact =
          await FlutterContactPicker.pickEmailContact();
          print(contact);
          setState(() {
            _emailContact = contact;
          });
        },
      ),
      ElevatedButton(
        child: const Text("pick full contact"),
        onPressed: () async {
          final FullContact contact =
          (await FlutterContactPicker.pickFullContact());
          setState(() {
            _contact = contact.toString();
            _contactPhoto = contact.photo?.asWidget();
          });
        },
      ),
      ElevatedButton(
        child: const Text('Check permission'),
        onPressed: () async {
          final granted = await FlutterContactPicker.hasPermission();
          showDialog(
              context: context,
              builder: (context) => AlertDialog(
                  title: const Text('Granted: '), content: Text('$granted')));
        },
      ),
      ElevatedButton(
        child: const Text('Request permission'),
        onPressed: () async {
          final granted = await FlutterContactPicker.requestPermission();
          showDialog(
              context: context,
              builder: (context) => AlertDialog(
                  title: const Text('Granted: '), content: Text('$granted')));
        },
      ),
    ];
  }
}

联系人姓名已设置

/// your code

TextEditingController _phn = TextEditingController();

_phn = contact.phoneNumber!.number
    .removeAllWhiteSpace()
    .replaceFirst('+91', '')
    .toString();

/// Modify as

_phn.text = contact.phoneNumber!.number
    .removeAllWhiteSpace()
    .replaceFirst('+91', '')
    .toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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