skip to Main Content

I have a list of contact name with permission handler and I would like to get the name for every contact in single contact page

Here’s What I’ve so far, but I’m getting an error

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

class ContactFetch extends StatefulWidget {
  static const String screenroute = "ContactFetch";
  const ContactFetch({super.key});

  get displayName => null;
  get phones => null;

  @override
  State<ContactFetch> createState() => _ContactState();
}

class _ContactState extends State<ContactFetch> {
  @override
  void initState() {
    super.initState();
    _askPermissions();
  }

  Future<void> _askPermissions() async {
    PermissionStatus permissionStatus = await _getContactPermission();
    if (permissionStatus != PermissionStatus.granted) {
      _handleInvalidPermissions(permissionStatus);
    }
  }

  Future<PermissionStatus> _getContactPermission() async {
    PermissionStatus permission = await Permission.contacts.status;
    if (permission != PermissionStatus.granted &&
        permission != PermissionStatus.permanentlyDenied) {
      PermissionStatus permissionStatus = await Permission.contacts.request();
      return permissionStatus;
    } else {
      return permission;
    }
  }

  void _handleInvalidPermissions(PermissionStatus permissionStatus) {
    if (permissionStatus == PermissionStatus.denied) {
      const snackBar = SnackBar(content: Text('Access to contact data denied'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    } else if (permissionStatus == PermissionStatus.permanentlyDenied) {
      const snackBar =
          SnackBar(content: Text('Contact data not available on device'));
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    }
  }

  Future<List<Contact>>? reqContact;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Contacts List'),
      ),
      body: Column(
        children: [
          ElevatedButton(
              onPressed: () {
                setState(() {
                  reqContact =
                      ContactsService.getContacts() as Future<List<Contact>>?;
                });
              },
              child: const Text("Load Contact")),
          Expanded(
              child: FutureBuilder(
                  future: reqContact,
                  builder: (context, snp) {
                    if (snp.connectionState == ConnectionState.done) {
                      var contacts = snp.data;

                      if (contacts != null) {
                        return ListView.builder(
                            shrinkWrap: true,
                            itemCount: contacts.length,
                            itemBuilder: (context, index) {
                              Contact contact = contacts[index];

                              return ListTile(
                                title: Text(' ${contact.displayName}'),
                                leading: CircleAvatar(
                                  child: Text("A"),
                                ),
                                subtitle: Text(contact.phones?.single.value ??
                                    "not found"),
                                onTap: () {
                                  Navigator.pushNamed(
                                      context, Individualpage.screenroute);
                                },
                              );
                            });
                      }
                      return Container();
                    }
                    return Container();
                  })),
        ],
      ),
    );
  }
}
import 'package:contacts_service/contacts_service.dart';
import 'package:flutter/material.dart';

class Individualpage extends StatefulWidget {
  static const String screenroute = "IndividualPage";
  const Individualpage({super.key});

  @override
  State<Individualpage> createState() => _IndividualpageState();
}

class _IndividualpageState extends State<Individualpage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
      backgroundColor: Colors.blue,
      leading: CircleAvatar(
        child: Text("A"),
      ),
      title: Text("${Contact(displayName: )}"),//error
    ));
  }
}

Then this is the error I’m getting.

title: Text("${Contact(displayName: )}")

2

Answers


  1. Looks like you are facing issue in sending data from one screen to other screen in flutter.
    You can pass data via arguments while routing to Individualpage like :

    Navigator.of(context).pushNamed(
              Individualpage.screenroute,
              arguments: {
                'title':'${contact.displayName}'
              });  //pass arguments with routing
    

    and now on target page you can get the arguments like this :

    import 'package:contacts_service/contacts_service.dart';
    import 'package:flutter/material.dart';
    class Individualpage extends StatefulWidget {
      static const String screenroute = "IndividualPage";
      const Individualpage({super.key});
    
    final routesArguments=ModalRoute.of(context).settings.arguments as Map<String,String>;  //get route arguments
    
      @override
      State<Individualpage> createState() => _IndividualpageState();
    }
    
    class _IndividualpageState extends State<Individualpage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
          backgroundColor: Colors.blue,
          leading: CircleAvatar(
            child: Text("A"),
          ),
          title: Text("${routesArguments['title']}"),//get value from route arguments
        ));
      }
    }
    

    and similarly you can pass more values in json with Navigator.of(context).pushNamed function.

    Login or Signup to reply.
  2. Yes you are thinking in right direction but there is minor changes in your implementation.

    • First when you pass the arguments in pushNamed give named parameter arguments in that and pass your data..
    class ContactFetch extends StatefulWidget {
      static const String screenroute = "ContactFetch";
      const ContactFetch({super.key});
    
      get displayName => null;
      get phones => null;
    
      @override
      State<ContactFetch> createState() => _ContactState();
    }
    
    class _ContactState extends State<ContactFetch> {
      @override
      void initState() {
        super.initState();
        _askPermissions();
      }
    
      Future<void> _askPermissions() async {
        PermissionStatus permissionStatus = await _getContactPermission();
        if (permissionStatus != PermissionStatus.granted) {
          _handleInvalidPermissions(permissionStatus);
        }
      }
    
      Future<PermissionStatus> _getContactPermission() async {
        PermissionStatus permission = await Permission.contacts.status;
        if (permission != PermissionStatus.granted &&
            permission != PermissionStatus.permanentlyDenied) {
          PermissionStatus permissionStatus = await Permission.contacts.request();
          return permissionStatus;
        } else {
          return permission;
        }
      }
    
      void _handleInvalidPermissions(PermissionStatus permissionStatus) {
        if (permissionStatus == PermissionStatus.denied) {
          const snackBar = SnackBar(content: Text('Access to contact data denied'));
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
        } else if (permissionStatus == PermissionStatus.permanentlyDenied) {
          const snackBar =
              SnackBar(content: Text('Contact data not available on device'));
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
        }
      }
    
      Future<List<Contact>>? reqContact;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Contacts List'),
          ),
          body: Column(
            children: [
              ElevatedButton(
                  onPressed: () {
                    setState(() {
                      reqContact =
                          ContactsService.getContacts() as Future<List<Contact>>?;
                    });
                  },
                  child: const Text("Load Contact")),
              Expanded(
                  child: FutureBuilder(
                      future: reqContact,
                      builder: (context, snp) {
                        if (snp.connectionState == ConnectionState.done) {
                          var contacts = snp.data;
    
                          if (contacts != null) {
                            return ListView.builder(
                                shrinkWrap: true,
                                itemCount: contacts.length,
                                itemBuilder: (context, index) {
                                  Contact contact = contacts[index];
    
                                  return ListTile(
                                    title: Text(' ${contact.displayName}'),
                                    leading: CircleAvatar(
                                      child: Text("A"),
                                    ),
                                    subtitle: Text(contact.phones?.single.value ??
                                        "not found"),
                                    onTap: () {
                                      Navigator.pushNamed(
                                          context, arguments: {Individualpage.screenroute: contact});
                                    },
                                  );
                                });
                          }
                          return Container();
                        }
                        return Container();
                      })),
            ],
          ),
        );
      }
    }
    
    • Now in your single contact page you need to fetch your arguments…
    import 'package:contacts_service/contacts_service.dart';
    import 'package:flutter/material.dart';
    
    class Individualpage extends StatefulWidget {
      static const String screenroute = "IndividualPage";
      const Individualpage({super.key});
    
      @override
      State<Individualpage> createState() => _IndividualpageState();
    }
    
    class _IndividualpageState extends State<Individualpage> {
        late Contact contact;
    
    
        final arg = ModalRoute.of(context)?.settings.arguments;
            if(arg is Map){
          if((arg).containsKey(Individualpage.screenroute)){
            contact = arg;
          }
        }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
          backgroundColor: Colors.blue,
          leading: CircleAvatar(
            child: Text("A"),
          ),
          title: Text("${contact.displayName}"),//error
        ));
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search