首页 > 解决方案 > 无法在列表视图中加载变量

问题描述

说明:我正在尝试在 ListView 中显示 json 文件中的值。我创建了一个类来读取 json 文件并从键中获取值。这很好用,但是,我无法将键值携带到 ListView 中。我使用名为“EmployeeInfo”的单独类获取键值,并使用名为“jsonContent”的方法读取 json 文件内容。到目前为止,我可以实例化类,执行方法并将类变量打印到控制台上。但是,我无法将此类变量值加载到 ListView 标题中。

我无法在此代码中加载我的变量,但能够通过 :print(jsonrd.EmployeeJson[“Name”]

import 'package:flutter/material.dart';
import 'package:emas_app/Dependant.dart' as Dep;

import 'dart:convert';

void main() => runApp(new Fourth());



class Fourth extends StatefulWidget {

  @override
  MemberInfoState createState() => new MemberInfoState();
}
class MemberInfoState extends State<Fourth>{
  List  data;
  @override
  Widget build(BuildContext context) {
    var  jsonrd = new Dep.EmployeeInfo(); // Go to the house and open the door
    jsonrd.jsonContent(); // E

    return new Scaffold(

      body:  new Container(

        child: new Center(
          child:new FutureBuilder(
            future: DefaultAssetBundle
                .of(context)
                .loadString('assets/MemberInfo.json'),
            builder: (context,snapshot){

              var mydata = JSON.decode(snapshot.data.toString());
              print("mydata: " + mydata.toString());
              var jsondata = new Dep.EmployeeInfo();
              jsondata.jsonContent();
              final name = jsondata.EmployeeJSON["Name"].toString();

              return new ListView.builder(
                itemBuilder:(BuildContext context,int index){
                  return new Card(
                    child:new Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        new ListTile(
                          title: new Text("Name " ),
                          subtitle: new Text(name),
                        ),
                        new ListTile(
                          title: new Text("Identification " ),
                          subtitle: new Text(  mydata[index]["Employee"]["Identification"]),
                        ),
                        new ListTile(
                          title: new Text("Company " ),
                          subtitle: new Text(  mydata[index]["Employee"]["Company"]),
                        ),
                        new ListTile(
                          title: new Text("Date Of Birth " ),
                          subtitle: new Text(  mydata[index]["Employee"]["DateOfBirth"]),
                        ),

                        const Divider(
                          color: Colors.white,
                          height: 50.0,
                        ),

                        new MaterialButton(
                            color: Colors.indigo,
                            height:50.0,
                            minWidth: 50.0,
                            textColor: Colors.white,
                            child: new Text("More"),
                            onPressed: () => print(jsonrd.EmployeeJSON["Name"])

                            ),
                      ],

                    ),

                  );





                },
                itemCount: mydata ==  null ? 0 : mydata.length,
              );


            },
          ),
//
//
        ),

      ),
    );
  }
}

调用 Json(代码):

导入“包:颤振/material.dart”;

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;


final String url = "http://crm.emastpa.com.my/MemberInfo.json";
List depData;



class EmployeeInfo {
//  String jsonContent;
  List data;
  String Employee;
  String empname;
  String empdep;
  Map <String, dynamic> EmployeeJSON = new Map<String, dynamic>();

  void jsonContent() {

    Future<String> getData() async {
      var res = await http.get(
          Uri.encodeFull("http://crm.emastpa.com.my/MemberInfo.json"),
          headers: {"Accept": "application/json"});

      var resBody = json.decode(res.body);
      this.data = resBody;

      this.EmployeeJSON = resBody[0]["Employee"];
      Employee = resBody[0]["Employee"]["Name"];
      depData = resBody[0]["Dependents"];

      this.empname = this.EmployeeJSON["Name"];
      this.empdep= depData[0]["Dependents"];
      return "Success!";
    }
    getData();
  }

}

输出 Performing hot reload... I/flutter (24432): mydata: null 在 1,696 毫秒内重新加载了 549 个库中的 8 个。I/flutter (24432): mydata: null I/flutter (24432): mydata: null I/flutter (24432): mydata: null I/flutter (24432): mydata: null 失去与设备的连接。

标签: jsondartflutter

解决方案


哇,你的代码真的很难。您在构建方法中执行了一个未来,而不仅仅是在 FutureBuilder 中期待它的结果。

我做了一个深刻的修改,仍然保持你想做的精神。

但是您应该真正创建一个返回员工列表的 Future,而不是在 FutureBuilder 中处理 html 响应。

import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;

final String url = "http://crm.emastpa.com.my/MemberInfo.json";

class EmployeeInfo {
  String Employee;
  String empname;
  String empdep;
  Map<String, dynamic> EmployeeJSON = new Map<String, dynamic>();
}

Future<String> jsonContent() async {
  var res = await http.get(
      Uri.encodeFull("http://crm.emastpa.com.my/MemberInfo.json"),
      headers: {"Accept": "application/json"});
  return res.body;
}

void main() => runApp(new Fourth());

class Fourth extends StatefulWidget {
  @override
  MemberInfoState createState() => new MemberInfoState();
}

class MemberInfoState extends State<Fourth> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: new Scaffold(
        body: new Container(
          child: new Center(
            child: new FutureBuilder<String>(
              future: jsonContent(),
              builder: (context, snapshot) {
                if (snapshot?.hasData) {
                  var mydata = json.decode(snapshot.data);
                  final name = mydata[0]["Employee"]["Name"];

                  return new ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return new Card(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            new ListTile(
                              title: new Text("Name "),
                              subtitle: new Text(name),
                            ),
                            new ListTile(
                              title: new Text("Identification "),
                              subtitle: new Text(
                                  mydata[index]["Employee"]["Identification"]),
                            ),
                            new ListTile(
                              title: new Text("Company "),
                              subtitle: new Text(
                                  mydata[index]["Employee"]["Company"]),
                            ),
                            new ListTile(
                              title: new Text("Date Of Birth "),
                              subtitle: new Text(
                                  mydata[index]["Employee"]["DateOfBirth"]),
                            ),
                            const Divider(
                              color: Colors.white,
                              height: 50.0,
                            ),
                            new MaterialButton(
                              color: Colors.indigo,
                              height: 50.0,
                              minWidth: 50.0,
                              textColor: Colors.white,
                              child: new Text("More"),
                            ),
                          ],
                        ),
                      );
                    },
                    itemCount: mydata == null ? 0 : mydata.length,
                  );
                } else {
                  return CircularProgressIndicator();
                }
              },
            ),
          ),
        ),
      ),
    );
  }
}

推荐阅读