Shreyas Bhardwaj
Shreyas Bhardwaj

Reputation: 81

Get a single item from RestAPI using id as parameter in Flutter

I hope you all are doing safe. I have successfully implemented getContactList() from Rest API in ListView but now I want to get a single contact item when I click on a particular contact list item and display its fields in a TextFormField in flutter by passing the contact id as a parameter. I'm new to flutter and coding in general so I hope I could get my solution here. Thank You.

Sample Json Data:

{
    "total": "1",
    "contacts": {
        "193208": {
            "isPublished": true,
            "dateAdded": "2017-11-14T17:21:47+05:30",
            "dateModified": "2017-11-14T17:33:51+05:30",
            "createdBy": 4,
            "createdByUser": "Arul raj",
            "modifiedBy": 4,
            "modifiedByUser": "Arul raj",
            "id": 193208,
            "points": 0,
            "color": null,
            "fields": {
                "core": {
                    "points": {
                        "id": "47",
                        "label": "Points",
                        "alias": "points",
                        "type": "number",
                        "group": "core",
                        "object": "lead",
                        "is_fixed": "1",
                        "value": "0"
                    },
                    "firstname": {
                        "id": "2",
                        "label": "First Name",
                        "alias": "firstname",
                        "type": "text",
                        "group": "core",
                        "object": "lead",
                        "is_fixed": "1",
                        "value": "Richa"
                    },
                    "lastname": {
                        "id": "3",
                        "label": "Last Name",
                        "alias": "lastname",
                        "type": "text",
                        "group": "core",
                        "object": "lead",
                        "is_fixed": "1",
                        "value": "Kumari"
                    },
                    "...": {
                        "...": "...",
                    },
                    {
                        ....
                    }
        }
    }
}

API_Manager.dart:

import 'dart:convert';
import 'package:aritic/models/singleContactModel.dart';
import 'package:http/http.dart' as http;
import 'package:aritic/models/contactsModel.dart';
import 'dart:developer' as developer;

// ignore: camel_case_types
class API_Manager {
  Future<ContactsModel> getContacts() async {
    var client = http.Client();
    var contactsModel;
    String contacts_url =
        'https://example.com/api/contacts';
    String basicAuth = 'Basic exampleauthkey';
    try {
      var response = await client.get(contacts_url,
          headers: <String, String>{'authorization': basicAuth});
      //print(response.statusCode);
      //developer.log(response.body);
      if (response.statusCode == 200) {
        var jsonString = response.body;
        var jsonMap = json.decode(jsonString);
        contactsModel = ContactsModel.fromJson(jsonMap);
      }
    } catch (Exception) {
      return contactsModel;
    }
    return contactsModel;
  }

  Future<ContactsModel> getSingleContact(String id) async {
    var client = http.Client();
    var singleContactModel;
    String singleContactUrl =
        'https://example.com/api/contacts/id';
    String basicAuth = 'Basic exampleauthkey';
    try {
      var response = await client.get(singleContactUrl,
          headers: <String, String>{'authorization': basicAuth});
      print(response.statusCode);
      //developer.log(response.body);
      if (response.statusCode == 200) {
        var jsonString = response.body;
        var jsonMap = json.decode(jsonString);
        singleContactModel = SingleContactModel.fromJson(jsonMap);
      }
    } catch (Exception) {
      return singleContactModel;
    }
    return singleContactModel;
  }
}

View Single contact UI Code:

import 'package:flutter/material.dart';
import 'package:aritic/services/api_manager.dart';

class ViewContact extends StatefulWidget {

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

class _ViewContactState extends State<ViewContact> {
  bool isLoading = false;

  @override
  Widget build(BuildContext context) {
    API_Manager().getSingleContact();   //Need to pass id as parameter here
    return Scaffold(
      backgroundColor: Color(0xFFDAE0E2),
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        title: Text("View Contact"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            _topContainer(),
            DefaultTabController(
                length: 4, // length of tabs
                initialIndex: 0,
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      Container(
                        child: TabBar(
                          isScrollable: false,
                          unselectedLabelColor:
                              Colors.blueGrey[700].withOpacity(1),
                          labelColor: Colors.black,
                          indicatorColor: Colors.blueGrey[700],
                          labelPadding: EdgeInsets.symmetric(horizontal: 2.0),
                          tabs: [
                            Tab(text: 'Activity'),
                            Tab(text: 'Associations'),
                            Tab(text: 'About'),
                            Tab(text: 'Attachments'),
                          ],
                        ),
                      ),
                      _bottomContainer(),
                    ])),
          ],
        ),
      ),
    );
  }

  Widget _bottomContainer() {
    return SingleChildScrollView(
      child: Container(
          height: 400, //height of TabBarView
          decoration: BoxDecoration(
              border: Border(
                  top: BorderSide(
                      color: Colors.grey, width: 0.5))),
          child: TabBarView(children: <Widget>[
            _activityContainer(),
            _associationsContainer(),
            _aboutContainer(),
            _attachmentsContainer()
          ])),
    );
  }

  Widget _aboutContainer() {
    return Container(
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 10,
            ),
            Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              SizedBox(
                width: 3,
              ),
              Text('About Contact',
                  style: TextStyle(
                      fontSize: 17,
                      color: Colors.blueGrey[700],
                      fontWeight: FontWeight.bold)),
              SizedBox(
                width: 90,
              ),
              Container(
                width: 100,
                height: 30,
                child: RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5.0),
                      side: BorderSide(color: Colors.blueGrey[700])),
                  onPressed: () {},
                  color: Color(0xFFC9E8E9).withOpacity(0.5),
                  textColor: Colors.blueGrey[700],
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("Edit Contact",
                          style: TextStyle(
                              fontSize: 12, fontWeight: FontWeight.bold)),
                    ],
                  ),
                ),
              ),
              SizedBox(
                width: 3,
              ),
            ]),
            SizedBox(height: 10,),
            Padding(
              padding: const EdgeInsets.all(3.0),
              child: TextFormField(
                readOnly: true,
                keyboardType: TextInputType.text,
                decoration: InputDecoration(
                    labelText: 'First Name',
                    fillColor: Colors.white,
                    filled: true,
                    contentPadding: EdgeInsets.all(8)),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(3.0),
              child: TextFormField(
                readOnly: true,
                keyboardType: TextInputType.text,
                decoration: InputDecoration(
                    labelText: 'Last Name',
                    fillColor: Colors.white,
                    filled: true,
                    contentPadding: EdgeInsets.all(8)),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(3.0),
              child: TextFormField(
                readOnly: true,
                keyboardType: TextInputType.text,
                decoration: InputDecoration(
                    labelText: 'Email',
                    fillColor: Colors.white,
                    filled: true,
                    contentPadding: EdgeInsets.all(8)),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(3.0),
              child: TextFormField(
                readOnly: true,
                keyboardType: TextInputType.text,
                decoration: InputDecoration(
                    labelText: 'Phone Number',
                    fillColor: Colors.white,
                    filled: true,
                    contentPadding: EdgeInsets.all(8)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

I've removed all the unnecessary UI code and kept only the ones which will usable here.

EDIT, All contacts Page:

FutureBuilder<ContactsModel>(
                      future: _contactsModel,
                      builder: (BuildContext context,
                          AsyncSnapshot<ContactsModel> snapshot) {
                        if (snapshot.hasData) {
                          return ListView.separated(
                            shrinkWrap: true,
                            padding: const EdgeInsets.all(8),
                            itemCount: snapshot.data.contacts.length,
                            itemBuilder: (BuildContext context, int index) {
                              List keys = snapshot.data.contacts.keys.toList();
                              List values =
                                  snapshot.data.contacts.values.toList();
                              var contact = values[index]; //Single contact object here
                              final contactID = contact.id.toString();
                              return InkWell(
                                onTap: () {
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (_) => ViewContact(contact, contactID)));
                                },
                                child: Container(
                                  height: 50,
                                  color: Colors.white,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        contact.fields.all.firstname +
                                            " " +
                                            contact.fields.all.lastname,
                                        style: TextStyle(fontSize: 16),
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            },
                            separatorBuilder:
                                (BuildContext context, int index) {
                              return SizedBox(
                                height: 5,
                              );
                            },
                          );
                        } else
                          return Center(
                              child: CircularProgressIndicator(
                                  backgroundColor: Colors.blueGrey[700],
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                      Colors.cyan)));
                      }),

Upvotes: 0

Views: 1718

Answers (1)

Mohamed Inshaf
Mohamed Inshaf

Reputation: 395

you can pass the whole contact details using index and refer it from ViewContact(contactData) page ,then you have to add that controller to your textform feilds

import 'package:flutter/material.dart';
import 'package:aritic/services/api_manager.dart';

class ViewContact extends StatefulWidget {
 final contactData;
 ViewContact(this.contactData);

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

then you have to set all the textfeild controller to your data like

class _ViewContactState extends State<ViewContact> {
 bool isLoading = false;

  @override
 Widget build(BuildContext context) {

  TextEditingController name = TextEditingController();
    @override
    void initState() { 
      super.initState();
      name.text = widget.contactData.personNameexample
      }
TextFormField(
            readOnly: true,
            controller:name
            keyboardType: TextInputType.text,
            decoration: InputDecoration(
                labelText: 'Last Name',
                fillColor: Colors.white,
                filled: true,
                contentPadding: EdgeInsets.all(8)),
          ),

Upvotes: 1

Related Questions