Search code examples
flutterlistviewdartwidgetcontacts

Inserting new Widgets as List on Pressing Button in Flutter


I am making a screen like this which could select contacts from the phone book and insert the names as lists in my application. I want is that when I press Add caregiver(+) button it should select a contact and show the name. I made a Widget for the MOM part but whenever I click the button it rewrites the MOM to any contact that I select from the phone book.

I made this screen:

enter image description here

I also want to add Dad and Sister's Contact in the same manner as mom, but I am unable to do it

enter image description here

This is my code for the screen:

import 'package:epicare/NavigBar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:contact_picker/contact_picker.dart';

//Check contacts permission
Future<PermissionStatus> _getPermission() async {

  final PermissionStatus permission = await Permission.contacts.status;
  if (permission != PermissionStatus.granted &&
      permission != PermissionStatus.denied) {
    final Map<Permission, PermissionStatus> permissionStatus =
    await [Permission.contacts].request();
    return permissionStatus[Permission.contacts] ??
        PermissionStatus.undetermined;
  } else {
    return permission;
  }
}


class CaregiverScreen extends StatefulWidget {
  @override
  _CaregiverScreenState createState() => _CaregiverScreenState();
}

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

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  bool isSwitched = true;
  @override
  Widget build(BuildContext context) {
    //Size size = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: const Color(0xffE5E0A1),
        elevation: 0,
        centerTitle: true,
        title: Text(
          "Add Caregiver",
          style: TextStyle(
            fontSize: 15.0,
            color: Colors.black,
            fontFamily: 'Montserrat',
            fontWeight: FontWeight.normal,
          ),
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return Homepage();
                },
              ),
            );
          },
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 40),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  MaterialButton(
                    onPressed: () async {

                      final PermissionStatus permissionStatus = await _getPermission();
                      if (permissionStatus == PermissionStatus.granted) {
                        //We can now access our contacts here
                        // var contactNumber = openContactBook();
                        Contact contact = await _contactPicker.selectContact();
                        setState(() {
                          _contact = contact;
                        });
                      }
                      else {
                        //If permissions have been denied show standard cupertino alert dialog
                        showDialog(
                            context: context,
                            builder: (BuildContext context) => CupertinoAlertDialog(
                              title: Text('Permissions error'),
                              content: Text('Please enable contacts access '
                                  'permission in system settings'),
                              actions: <Widget>[
                                CupertinoDialogAction(
                                  child: Text('OK'),
                                  onPressed: () => Navigator.of(context).pop(),
                                )
                              ],
                            ));
                      }
                    },
                    color: const Color(0xffd4d411),
                    textColor: Colors.white,
                    child: Icon(
                      Icons.add,
                      size: 32,
                    ),
                    padding: EdgeInsets.all(3),
                    shape: CircleBorder(),
                  ),
                  Text(
                    'Add a Caregiver',
                    style: TextStyle(
                        fontFamily: 'Montserrat',
                        fontSize: 13,
                        color: const Color(0xff000000),
                        height: 1.5384615384615385,
                        fontWeight: FontWeight.w600),
                    textHeightBehavior:
                        TextHeightBehavior(applyHeightToFirstAscent: false),
                    textAlign: TextAlign.left,
                  )
                ],
              ),
                _contact == null ? Container() : CaregiversList(_contact.fullName),
            ],
          ),
        ),
      ),
    );
  }
Widget CaregiversList(String name){
    print(name);
    var c = name.split(' ');
    print(c[0]);
    var caregiver = c[0];
    var output = getInitials(string: caregiver, limitTo: 1);
    print(output);
    // var i = caregiver.codeUnitAt(0);
    // print(i);
    return Container(
    padding: EdgeInsets.symmetric(vertical: 20, horizontal: 27),
    child: Row(
      //crossAxisAlignment: CrossAxisAlignment.center,
      //mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        CircleAvatar(
          radius: 24,
          backgroundColor: const Color(0xffd4d411),
          child: CircleAvatar(
            radius: 22,
            backgroundColor: Colors.white,
            child: Text(
              output,
              style: TextStyle(
                fontFamily: 'Segoe UI',
                fontSize: 20,
                color: const Color(0xff000000),
              ),
            ),
          ),
        ),
        SizedBox(width: 19),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              caregiver,
              style: TextStyle(
                  fontFamily: 'Montserrat',
                  fontSize: 13,
                  color: const Color(0xff000000),
                  height: 1.5384615384615385,
                  fontWeight: FontWeight.w600),
              textHeightBehavior: TextHeightBehavior(
                  applyHeightToFirstAscent: false),
              textAlign: TextAlign.left,
            ),
            isSwitched
                ? Text(
                    "Activated",
                    style: TextStyle(
                        fontFamily: 'Montserrat',
                        fontSize: 10,
                        color: const Color(0x80232425),
                        fontWeight: FontWeight.w500),
                    textAlign: TextAlign.left,
                  )
                : Text(
                    "Disabled",
                    style: TextStyle(
                        fontFamily: 'Montserrat',
                        fontSize: 10,
                        color: const Color(0x80232425),
                        fontWeight: FontWeight.w500),
                    textAlign: TextAlign.left,
                  ),
          ],
        ),
        SizedBox(width: 143),
        FlutterSwitch(
          width: 40.0,
          height: 20.0,
          value: isSwitched,
          toggleSize: 15,
          borderRadius: 40.0,
          padding: 2.0,
          showOnOff: false,
          activeColor: const Color(0xffd4d411),
          activeToggleColor: Colors.white,
          inactiveColor: const Color(0xffDDDBAF),
          inactiveToggleColor: Colors.white,
          onToggle: (value) {
            setState(() {
              isSwitched = value;
              print(isSwitched);
            });
          },
        ),
      ],
    ),
  );

}
  String getInitials({String string, int limitTo}) {
    var buffer = StringBuffer();
    var split = string.split(' ');
    for (var i = 0 ; i < (limitTo ?? split.length); i ++) {
      buffer.write(split[i][0]);
    }
    return buffer.toString();
  }
}

Please help me out as i am new to Flutter. Thank you in advance :)


Solution

  • You need to manage Caregiverlist you've selected from contacts. for example

    class Caregiver {
      String name;
      bool isActive;
      
      Caregiver({this.name, this.isActive});
      
      factory Caregiver.fromJson(Map<String, dynamic> map) {
        if (map == null) return null;
        return Caregiver(name: map['name'] ?? "", 
                         isActive: map['isActive']);
      }
    }
    
    • initialize caregiver list

      List<Caregiver> _careList = [];
      
    • add Caregiver

      Contact contact = await _contactPicker.selectContact();
      setState(() {
        _careList.add(Caregiver(name: contact, isActive: true));
      });
      
    • show Caregiver list (To show ListView inside of Scrollview, add the following 3 lines.

      ListView.separated(
       physics: NeverScrollableScrollPhysics(),
       shrinkWrap: true,
       primary: false,
      itemBuilder: (context, index) {        
        return _caregiverWidget(index);
      },
      separatorBuilder: (_, __) => Divider(),
      itemCount: _careList.length);
      
    • Add new function

      Widget _caregiverWidget(int index) {
        Caregiver _caregiver = _careList[index];
        print(_caregiver.name);
        var c = _caregiver.name.split(' ');
        print(c[0]);
        var caregiver = c[0];
        var output = getInitials(string: caregiver, limitTo: 1);
        print(output);
        // var i = caregiver.codeUnitAt(0);
        // print(i);
        return Container(
          padding: EdgeInsets.symmetric(vertical: 20, horizontal: 27),
          child: Row(
            //crossAxisAlignment: CrossAxisAlignment.center,
            //mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              CircleAvatar(
                radius: 24,
                backgroundColor: const Color(0xffd4d411),
                child: CircleAvatar(
                  radius: 22,
                  backgroundColor: Colors.white,
                  child: Text(
                    output,
                    style: TextStyle(
                      fontFamily: 'Segoe UI',
                      fontSize: 20,
                      color: const Color(0xff000000),
                    ),
                  ),
                ),
              ),
              SizedBox(width: 19),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    caregiver,
                    style: TextStyle(
                        fontFamily: 'Montserrat',
                        fontSize: 13,
                        color: const Color(0xff000000),
                        height: 1.5384615384615385,
                        fontWeight: FontWeight.w600),
                    textHeightBehavior:
                        TextHeightBehavior(applyHeightToFirstAscent: false),
                    textAlign: TextAlign.left,
                  ),
                  _caregiver.isActive
                      ? Text(
                          "Activated",
                          style: TextStyle(
                              fontFamily: 'Montserrat',
                              fontSize: 10,
                              color: const Color(0x80232425),
                              fontWeight: FontWeight.w500),
                          textAlign: TextAlign.left,
                        )
                      : Text(
                          "Disabled",
                          style: TextStyle(
                              fontFamily: 'Montserrat',
                              fontSize: 10,
                              color: const Color(0x80232425),
                              fontWeight: FontWeight.w500),
                          textAlign: TextAlign.left,
                        ),
                ],
              ),
              SizedBox(width: 143),
              FlutterSwitch(
                width: 40.0,
                height: 20.0,
                value: _caregiver.isActive,
                toggleSize: 15,
                borderRadius: 40.0,
                padding: 2.0,
                showOnOff: false,
                activeColor: const Color(0xffd4d411),
                activeToggleColor: Colors.white,
                inactiveColor: const Color(0xffDDDBAF),
                inactiveToggleColor: Colors.white,
                onToggle: (value) {
                  setState(() {
                    _caregiver.isActive = value;
                    _careList.removeAt(index);
                    _careList.insert(index, _caregiver);
                  });
                },
              ),
            ],
          ),
        );
      }