0

I have an issue with a list I've created. I've added the numbers from my contacts list to a list. I want to use these numbers to send a text using phoneController, which takes a string of numbers:_phoneController.text = getAllContacts()._contacts.number[0]; But this returns an error.

import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/material.dart';
import 'package:telephony/telephony.dart';
import 'Contacts.dart';

class SendSMS extends StatefulWidget {
  const SendSMS({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<SendSMS> createState() => _SendSMS();
}

class _SendSMS extends State<SendSMS> {
  final Telephony telephony = Telephony.instance;

  final _formKey = GlobalKey<FormState>();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _msgController = TextEditingController();
  final Contacts contact = new Contacts();

  @override
  void initState() {
    super.initState();
     _phoneController.text = getAllContacts()._contacts.number[0];
    _msgController.text = 'User too far from route';
    _sendSMS();
    getAllContacts();
  }

  getAllContacts() async {
   // List<String> names = [];
    List<String> number = [];
    List<Contact> _contacts =
    (await ContactsService.getContacts(withThumbnails: false)).toList();
    setState(() {
      var contacts = _contacts;
    });
    _contacts.forEach((contact) {
      contact.phones!.toSet().forEach((phone) {
        //names.add("${contact.displayName}");
        number.add("${contact.phones!.elementAt(0).value}");
        print(number);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsetsDirectional.fromSTEB(0, 50, 8, 8),
                      child: Text('User too far from route!', style:TextStyle(fontSize: 35, fontStyle: FontStyle.normal))
                ),
                Padding (
                  padding: const EdgeInsets.all(5.0),
                  child: TextFormField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Message is empty';
                      }
                      return null;
                    },
                    decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: 'Phonenumber',
                        labelText: 'Number'),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(5),
                  child: TextFormField(
                    controller: _msgController,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'No message';
                      }
                    },
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Notifcation sent',
                    ),
                  ),
                ),
               // ElevatedButton( onPressed: () => _sendSMS(), child: const Text('Send notification')), Not needed since suppose to send automatically when entering TooFar page
              ],
            ),
          ),
        ),
      ),
    );
  }

  _sendSMS() async {
      telephony.sendSms(to: _phoneController.text, message: _msgController.text);
  }

  _getSMS() async {
    List<SmsMessage> _messages = await telephony.getInboxSms(
        columns: [SmsColumn.ADDRESS, SmsColumn.BODY],
        filter: SmsFilter.where(SmsColumn.ADDRESS).equals(_phoneController.text)
    );
  }
}

Below is code for Contacts

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

class Contacts extends StatefulWidget {

  @override
  _Contacts createState() => _Contacts();
}

class _Contacts extends State<Contacts> {
  List<Contact> contacts = [];
  @override
  void initState() {
    super.initState();
    getPermissions();
  }

  getPermissions() async {
    if (await Permission.contacts.request().isGranted) {
      getAllContacts();
    }
    ;
  }

  getAllContacts() async {
    List<String> names = [];
    List<String> phones = [];
    List<Contact> _contacts =
        (await ContactsService.getContacts(withThumbnails: false)).toList();
    setState(() {
      contacts = _contacts;
    });
    _contacts.forEach((contact) {
      contact.phones!.toSet().forEach((phone) {
        names.add("${contact.displayName}");
        phones.add("${contact.phones!.elementAt(0).value}");
        print(phones);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Contact info'),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
        child: Column(
          children: <Widget>[
            ListView.builder(
              shrinkWrap: true,
              itemCount: contacts.length,
              itemBuilder: (context, index) {
                Contact contact = contacts[index];
                return ListTile(
                    title: Text("${contact.displayName}"),
                    subtitle: Text("${contact.phones!.elementAt(0).value}"),
                    leading: CircleAvatar(child: Text(contact.initials())));
              },
            )
          ],
        ),
      ),
    );
  }
}
Jamal S
  • 1,649
  • 1
  • 19
  • 24
DipaJS
  • 11
  • 3

0 Answers0