Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何在flatter中显示从api获取的数据_Flutter_Dart - Fatal编程技术网

Flutter 如何在flatter中显示从api获取的数据

Flutter 如何在flatter中显示从api获取的数据,flutter,dart,Flutter,Dart,我想从API获取数据,并将其显示在Flatter应用程序中。我已经能够使用以下方法获取数据: @override void initState() { getprofile(widget.id); super.initState(); } Future<List<dynamic>> getprofile(int id) async { var response = await Network().getData('/auth/user

我想从API获取数据,并将其显示在Flatter应用程序中。我已经能够使用以下方法获取数据:

@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;
  }
@覆盖
void initState(){
getprofile(widget.id);
super.initState();
}
未来getprofile(int-id)异步{
var response=await Network().getData('/auth/user/$id');
var data=json.decode(response.body)['user'];
返回数据;
}
我想在这个小部件中使用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,
                                  ),
Widget getBody(){
返回脚手架(
主体:容器(
填充:仅限边设置(左:16,顶:1,右:16),
孩子:未来建设者(
未来:getprofile(widget.id),
生成器:(BuildContext上下文,
异步快照(快照){

//字符串名称=快照.data['name']; 如果(快照!=null){ 返回列表视图( 儿童:[ 容器( 装饰:盒子装饰( 梯度:线性梯度( 开始:Alignment.topCenter, 结束:对齐。底部中心, 颜色:[颜色。白色,颜色。白色]), 子:容器( 宽度:double.infinity, 高度:350.0, 儿童:中心( 子:列( crossAxisAlignment:crossAxisAlignment.center, mainAxisAlignment:mainAxisAlignment.center, 儿童:[ 大小盒子( 身高:10.0, ), 正文( “$name”, 样式:TextStyle( 字体大小:22.0, 颜色:颜色。灰色, ), ), 大小盒子( 身高:10.0, ),

对Response对象使用可序列化类映射

示例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"
        }
      }
    }
  }
}
您的样本可序列化类

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)),
    };
}
现在您可以作为对象访问值

sampleSerializableModel.Glossary.title
从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');
  }
}

您所做的一切都很好,您只需将
AsyncSnapshot snapshot
更改为
AsyncSnapshot snapshot
,因为您只有一个对象,而不是一个列表

if (snapshot != null) {
在将来的构建中,您将始终获得快照,但在使用它之前,您必须检查是否有数据或是否正在加载

if (snapshot.hasData) {


用于生成可序列化的classString name=snapshot.data['name'];运行后:在null上调用了方法“[]”。尝试调用:[](“name”)问题没有解决是的只要在确定数据存在时在if中获取名称即可
if (snapshot != null) {
if (snapshot.hasData) {
if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) {