android - 如何使用 flutter 访问 JSON 对象?

标签 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/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;
      });
    }
  }
}

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

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

最佳答案

尝试这个,

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'];
  }
}

关于android - 如何使用 flutter 访问 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59873000/

相关文章:

ios - swift 4 : Mask not working for UIImage?

javascript - 长轮询以更新 DOM,同时保留来自 jQuery 的累积属性

java - 使用 Jackson 将映射编码到对象

ios - UICollectionView 在 insertSections 上崩溃,endItemAnimationsWithInvalidationContext :tentativelyForReordering:

android - API - 适用于 iOS 和 Android 的图像尺寸(不同屏幕尺寸)- 优化

javascript - JSON.stringify 和 $http 请求

Android USB 音频作为主要音频

Android以编程方式查找ViewByID

android - 将mysql数据库中的视频url显示到listview

androidquery AjaxStatus -103 错误