Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/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
Android 如何使用flatter访问JSON对象?_Android_Ios_Json_Flutter_Dart - Fatal编程技术网

Android 如何使用flatter访问JSON对象?

Android 如何使用flatter访问JSON对象?,android,ios,json,flutter,dart,Android,Ios,Json,Flutter,Dart,如何访问JSON对象 获取Employee Title=null如何直接使用该对象 像这样获得正确的输出Text('Employee Title=${list[0].Title}')还是直接使用模型对象的任何其他方式 正确的方法是什么 import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:flutter/cupe

如何访问JSON对象

获取
Employee Title=null
如何直接使用该对象

像这样获得正确的输出
Text('Employee Title=${list[0].Title}')
还是直接使用模型对象的任何其他方式

正确的方法是什么

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


class EmployeeModel {
  int userId;
  int id;
  String title;
  String body;

  EmployeeModel({this.userId, this.id, this.title, this.body});

  EmployeeModel.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    body = json['body'];
  }
}
class EmployeePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return EmployeePageState();
  }
}

class EmployeePageState extends State<EmployeePage> {
  EmployeeModel model = EmployeeModel();
  List<EmployeeModel> list = List();
  var isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Employee Title = ${model.title}'),
        ),
        body: isLoading
            ? Center(
          child: CircularProgressIndicator(),
        ):Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[

                ])));
  }


  @override
  void initState() {
    super.initState();
    getEmployee(2);
  }

  getEmployee(int id) async {
    setState(() {
      isLoading = true;
    });
    final response =
        await http.get("https://jsonplaceholder.typicode.com/posts?userId=$id");
    if (response.statusCode == 200) {
      list = (json.decode(response.body) as List)
          .map((data) => new EmployeeModel.fromJson(data))
          .toList();
      setState(() {
        isLoading = false;
      });
    }
  }
}
导入'dart:convert';
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
进口“包装:颤振/cupertino.dart”;
类雇员模型{
int用户标识;
int-id;
字符串标题;
弦体;
EmployeeModel({this.userId,this.id,this.title,this.body});
EmployeeModel.fromJson(映射json){
userId=json['userId'];
id=json['id'];
title=json['title'];
body=json['body'];
}
}
类EmployeePage扩展StatefulWidget{
@凌驾
状态createState(){
//TODO:实现createState
返回EmployeePageState();
}
}
类EmployeePageState扩展了状态{
EmployeeModel=EmployeeModel();
List=List();
var isLoading=false;
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
title:Text('Employee title=${model.title}'),
),
主体:卸载
?中心(
子对象:CircularProgressIndicator(),
):中心(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
])));
}
@凌驾
void initState(){
super.initState();
一名雇员(2名);
}
getEmployee(int-id)异步{
设置状态(){
isLoading=true;
});
最后答复=
等待http.get(“https://jsonplaceholder.typicode.com/posts?userId=$id”);
如果(response.statusCode==200){
list=(json.decode(response.body)作为列表)
.map((数据)=>newEmployeeModel.fromJson(数据))
.toList();
设置状态(){
isLoading=false;
});
}
}
}
我的代码运行良好,但我想知道这是正确的方法吗? 这边
Text('Employee Title=${list[0].Title}')
或者,如果我想直接使用对象,该怎么办

我的代码运行良好,但我想知道这是正确的方法吗? 这边
Text('Employee Title=${list[0].Title}')
或者,如果我想直接使用object,方法是什么?

您从未从json初始化模型,因此模型的所有属性都为空。试着这样做:

    if (response.statusCode == 200) {
      final employees = json.decode(response.body);
      list = (employees as List)
          .map((data) => new EmployeeModel.fromJson(data))
          .toList();
      setState(() {
        model = new EmployeeModel.fromJson(employees[0]);
        isLoading = false;
      });
    }

我有两个模型课:

class EmployeeList {
  final List<Employee> employees;

  EmplyeeList({
    this.employees,
});

  factory EmployeeList.fromJson(List<dynamic> parsedJson) {

    List<Employee> employees = new List<Employee>();
    employees = parsedJson.map((i)=>Employee.fromJson(i)).toList();

    return new EmployeeList(
      employees: employees
    );
  }
}

class Employee{
  final String id;
  final String title;
  final String body;
  final String userId;


  Employee({
  String userId;
  String id;
  String title;
  String body;

}) ;

  factory Employee.fromJson(Map<String, dynamic> json){
    return new Employee(
      id: json['id'],
      userId:[userId]
      title: json['title'],
      body: json['body'],
    );
  }

}
class员工列表{
最终员工名单;
雇主({
这是我的员工,
});
FactoryEmployeeList.fromJson(List parsedJson){
列出员工=新列表();
employees=parsedJson.map((i)=>Employee.fromJson(i)).toList();
返回新员工列表(
雇员:雇员
);
}
}
班级员工{
最终字符串id;
最后的字符串标题;
最终管柱体;
最终字符串用户标识;
雇员({
字符串用户标识;
字符串id;
字符串标题;
弦体;
}) ;
factory Employee.fromJson(映射json){
返回新员工(
id:json['id'],
userId:[用户id]
标题:json['title'],
body:json['body'],
);
}
}
也许还可以考虑使用FutureBuilder…从Flatter文档:

试试这个

import 'dart:convert';

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: EmployeePage(),
    );
  }
}

class EmployeePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => EmployeePageState();
}

class EmployeePageState extends State<EmployeePage> {
  Future<List<EmployeeModel>> _employeeList;

  @override
  void initState() {
    _employeeList = _getEmployee(2);
    super.initState();
  }

  Future<List<EmployeeModel>> _getEmployee(int id) async {
    final response = await http.get(
      "https://jsonplaceholder.typicode.com/posts?userId=$id",
    );
    if (response.statusCode == 200) {
      final jsonBody = json.decode(response.body) as List;
      return jsonBody.map((data) => new EmployeeModel.fromJson(data)).toList();
    } else
      throw Exception("Unable to get Employee list");
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<EmployeeModel>>(
      future: _employeeList,
      builder: (context, snapshot) {
        print(snapshot);
        if (snapshot.hasData)
          return _buildBody(snapshot.data);
        else if (snapshot.hasError)
          return _buildErrorPage(snapshot.error);
        else
          return _buildLoadingPage();
      },
    );
  }

  Widget _buildBody(List<EmployeeModel> employeeList) => Scaffold(
        appBar: AppBar(
          title: Text('Employee Title = ${employeeList[0].title}'),
        ),
        body: ListView.builder(
          itemCount: employeeList.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(employeeList[index].title),
            );
          },
        ),
      );

  Widget _buildErrorPage(error) => Material(
        child: Center(
          child: Text("ERROR: $error"),
        ),
      );

  Widget _buildLoadingPage() => Material(
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
}

class EmployeeModel {
  int userId;
  int id;
  String title;
  String body;

  EmployeeModel({this.userId, this.id, this.title, this.body});

  EmployeeModel.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    body = json['body'];
  }
}

导入'dart:convert';
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
void main()=>runApp(MyApp());
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
主页:EmployeePage(),
);
}
}
类EmployeePage扩展StatefulWidget{
@凌驾
State createState()=>EmployeePageState();
}
类EmployeePageState扩展了状态{
未来雇员名单;
@凌驾
void initState(){
_employeeList=\u getEmployee(2);
super.initState();
}
Future\u getEmployee(int-id)异步{
最终响应=等待http.get(
"https://jsonplaceholder.typicode.com/posts?userId=$id“,
);
如果(response.statusCode==200){
final jsonBody=json.decode(response.body)作为列表;
返回jsonBody.map((数据)=>newEmployeeModel.fromJson(数据)).toList();
}否则
抛出异常(“无法获取员工列表”);
}
@凌驾
小部件构建(构建上下文){
回归未来建设者(
未来:_员工名单,
生成器:(上下文,快照){
打印(快照);
if(snapshot.hasData)
返回构建体(snapshot.data);
else if(snapshot.hasrerror)
返回_buildErrorPage(snapshot.error);
其他的
返回_buildLoadingPage();
},
);
}
Widget\u buildBody(List employeeList)=>Scaffold(
appBar:appBar(
title:Text('Employee title=${employeeList[0].title}'),
),
正文:ListView.builder(
itemCount:employeeList.length,
itemBuilder:(上下文,索引){
返回列表块(
标题:文本(员工列表[索引].标题),
);
},
),
);
小部件构建错误页面(错误)=>材料(
儿童:中心(
子项:文本(“错误:$ERROR”),
),
);
小部件_buildLoadingPage()=>材质(
儿童:中心(
子对象:CircularProgressIndicator(),
),
);
}
类雇员模型{
int用户标识;
int-id;
字符串标题;
弦体;
EmployeeModel({this.userId,this.id,this.title,this.body});
EmployeeModel.fromJson(映射json){
userId=json['userId'];
id=json['id'];
title=json['title'];
body=json['body'];
}
}