【问题标题】:how i can display data fetching from api in flutter我如何在颤动中显示从 api 获取的数据
【发布时间】:2021-06-16 17:57:02
【问题描述】:

我想从 API 中获取数据并将其显示在 Flutter 应用中。我已经能够使用这种方法获取数据:

@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;
  }

我想在这个小部件中使用 ListView builder 显示它: 在这种情况下如何显示变量名称?

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,
                                  ),

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您所做的一切都很好,您只需将AsyncSnapshot&lt;List&lt;dynamic&gt;&gt; snapshot 更改为AsyncSnapshot&lt;dynamic&gt; snapshot,因为您只有一个对象而不是列表。你必须改变的另一件事是

    if (snapshot != null) {
    

    使用 Future 构建,您将获得快照,但您必须在使用之前检查是否有数据或是否正在加载。

    if (snapshot.hasData) {
    

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

    【讨论】:

    • 字符串名称 = 快照.data['name'];运行后:在 null 上调用了方法“[]”。尝试调用:[]("name") 问题尚未解决
    • 当您确定数据存在时,只需在 if 中获取名称
    【解决方案2】:

    从 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 是数据模型。 从 api caling 函数获取数据

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

    【讨论】:

      【解决方案3】:

      对你的响应对象使用可序列化的类映射

      Json 响应示例

      {
        "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"
              }
            }
          }
        }
      }
      

      您的 sampleSerializable 类

      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)),
          };
      }
      

      并在 getprofile 方法中映射您的响应

       SampleSerializable sampleSerializableModel = SampleSerializable.fromJson(response);
      

      现在您可以将值作为对象访问

      sampleSerializableModel.Glossary.title
      

      【讨论】:

      猜你喜欢
      • 2020-12-17
      • 2019-10-20
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      相关资源
      最近更新 更多