0

I want to fetch the data from API and display it in flutter app. I've been able to fetch the data using this methode :

@override
  void initState() {
    getprofile(widget.id);
    super.initState();
  }

  Future<List<dynamic>> getprofile(int id) async {
    var response = await Network().getData('/auth/user/$id');

    var data = json.decode(response.body)['user'];
  
    return data;
  }

and i want to display it using ListView builder in this widget : how i can display the varaiable name in this case ?

Widget getBody() {
    return Scaffold(
      body: Container(
          padding: EdgeInsets.only(left: 16, top: 1, right: 16),
          child: FutureBuilder(
              future: getprofile(widget.id),
              builder: (BuildContext context,
                  AsyncSnapshot<List<dynamic>> snapshot) {
               // String name = snapshot.data['name'];
                 if (snapshot != null) {
                  return ListView(
                    children: [
                      Container(
                          decoration: BoxDecoration(
                              gradient: LinearGradient(
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                  colors: [Colors.white, Colors.white])),
                          child: Container(
                            width: double.infinity,
                            height: 350.0,
                            child: Center(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  
                                  SizedBox(
                                    height: 10.0,
                                  ),
                                  Text(
                                    "$name",
                                    style: TextStyle(
                                      fontSize: 22.0,
                                      color: Colors.grey,
                                    ),
                                  ),
                                  SizedBox(
                                    height: 10.0,
                                  ),

enter image description here

3 Answers 3

1

Use serializable class map with your responce object

Sample Json responce

{
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

Your sampleSerializable class

import 'dart:convert';

SampleSerializable sampleSerializableFromJson(String str) => SampleSerializable.fromJson(json.decode(str));

String sampleSerializableToJson(SampleSerializable data) => json.encode(data.toJson());

class SampleSerializable {
    SampleSerializable({
        this.glossary,
    });

    final Glossary glossary;

    factory SampleSerializable.fromJson(Map<String, dynamic> json) => SampleSerializable(
        glossary: json["glossary"] == null ? null : Glossary.fromJson(json["glossary"]),
    );

    Map<String, dynamic> toJson() => {
        "glossary": glossary == null ? null : glossary.toJson(),
    };
}

class Glossary {
    Glossary({
        this.title,
        this.glossDiv,
    });

    final String title;
    final GlossDiv glossDiv;

    factory Glossary.fromJson(Map<String, dynamic> json) => Glossary(
        title: json["title"] == null ? null : json["title"],
        glossDiv: json["GlossDiv"] == null ? null : GlossDiv.fromJson(json["GlossDiv"]),
    );

    Map<String, dynamic> toJson() => {
        "title": title == null ? null : title,
        "GlossDiv": glossDiv == null ? null : glossDiv.toJson(),
    };
}

class GlossDiv {
    GlossDiv({
        this.title,
        this.glossList,
    });

    final String title;
    final GlossList glossList;

    factory GlossDiv.fromJson(Map<String, dynamic> json) => GlossDiv(
        title: json["title"] == null ? null : json["title"],
        glossList: json["GlossList"] == null ? null : GlossList.fromJson(json["GlossList"]),
    );

    Map<String, dynamic> toJson() => {
        "title": title == null ? null : title,
        "GlossList": glossList == null ? null : glossList.toJson(),
    };
}

class GlossList {
    GlossList({
        this.glossEntry,
    });

    final GlossEntry glossEntry;

    factory GlossList.fromJson(Map<String, dynamic> json) => GlossList(
        glossEntry: json["GlossEntry"] == null ? null : GlossEntry.fromJson(json["GlossEntry"]),
    );

    Map<String, dynamic> toJson() => {
        "GlossEntry": glossEntry == null ? null : glossEntry.toJson(),
    };
}

class GlossEntry {
    GlossEntry({
        this.id,
        this.sortAs,
        this.glossTerm,
        this.acronym,
        this.abbrev,
        this.glossDef,
        this.glossSee,
    });

    final String id;
    final String sortAs;
    final String glossTerm;
    final String acronym;
    final String abbrev;
    final GlossDef glossDef;
    final String glossSee;

    factory GlossEntry.fromJson(Map<String, dynamic> json) => GlossEntry(
        id: json["ID"] == null ? null : json["ID"],
        sortAs: json["SortAs"] == null ? null : json["SortAs"],
        glossTerm: json["GlossTerm"] == null ? null : json["GlossTerm"],
        acronym: json["Acronym"] == null ? null : json["Acronym"],
        abbrev: json["Abbrev"] == null ? null : json["Abbrev"],
        glossDef: json["GlossDef"] == null ? null : GlossDef.fromJson(json["GlossDef"]),
        glossSee: json["GlossSee"] == null ? null : json["GlossSee"],
    );

    Map<String, dynamic> toJson() => {
        "ID": id == null ? null : id,
        "SortAs": sortAs == null ? null : sortAs,
        "GlossTerm": glossTerm == null ? null : glossTerm,
        "Acronym": acronym == null ? null : acronym,
        "Abbrev": abbrev == null ? null : abbrev,
        "GlossDef": glossDef == null ? null : glossDef.toJson(),
        "GlossSee": glossSee == null ? null : glossSee,
    };
}

class GlossDef {
    GlossDef({
        this.para,
        this.glossSeeAlso,
    });

    final String para;
    final List<String> glossSeeAlso;

    factory GlossDef.fromJson(Map<String, dynamic> json) => GlossDef(
        para: json["para"] == null ? null : json["para"],
        glossSeeAlso: json["GlossSeeAlso"] == null ? null : List<String>.from(json["GlossSeeAlso"].map((x) => x)),
    );

    Map<String, dynamic> toJson() => {
        "para": para == null ? null : para,
        "GlossSeeAlso": glossSeeAlso == null ? null : List<dynamic>.from(glossSeeAlso.map((x) => x)),
    };
}

And map your responce in getprofile method

 SampleSerializable sampleSerializableModel = SampleSerializable.fromJson(response);

Now you can access value as object

sampleSerializableModel.Glossary.title
Sign up to request clarification or add additional context in comments.

1 Comment

Use app.quicktype.io to generate Serializable class
0

All you are doing is fine, you just have to change AsyncSnapshot<List<dynamic>> snapshot to AsyncSnapshot<dynamic> snapshot since you are having just one object not a list. The other thing that you have to change is

if (snapshot != null) {

With Future build you will aways get the snapshot but you have to check if there is a data or if is loading before you use it.

if (snapshot.hasData) {

or

if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {

2 Comments

String name = snapshot.data['name']; after running : The method '[]' was called on null. Tried calling: []("name") the problem not solved yet
Just get the name inside the if when you are sure that the data is there
0

fetching data from api

Future<TrueOrFalse > freeaccess() async {
  String userid = await getUserId();
  var map = new Map<String, String>();
  map['userid'] = userid;
  var response = await http
      .post(Constants.ApiBaseUrl + '/free_access_check.php', body: map);
  if (response.statusCode == 200) {
    print("freeaccess response userid $userid" + response.body);

    TrueOrFalse trueOrFalse = TrueOrFalse.fromJson(json.decode(response.body));

    if (trueOrFalse.status == "sucess") {
      return true;
    } else {
      return false;
    }
  } else {
    throw Exception('Failed to crate login session');
  }
}

TrueOrFalse is the data model. getting data from the api caling function

@override
  void initState() {
    freeaccess().then((value) => {
          print(value);
        });
    super.initState();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.