【问题标题】:Class has no instance getter - json model类没有实例 getter - json 模型
【发布时间】:2020-10-08 21:20:04
【问题描述】:

我正在尝试解决一个问题,我无法通过谷歌搜索或在此处找到任何答案,所以这是我的问题。

我正在尝试从我自己的 json 测试服务器获取 json 数据:http://my-json-server.typicode.com/tariksalihovic/innbo/receipt

json 数据是嵌套的,我正在尝试获取 "receiptLines": 我已遵循嵌套 json 数据的教程,但无法解决如何从收据行打印 productNumber 字符串的问题。

至于我的代码,我尝试使用data[index].productNumber,但出现以下错误:

Class 'Receipt' has no instance getter 'productNumber'. Receiver: Instance of 'Receipt' Tried calling: productName

请注意,我可以从第一级获取和打印字符串,但不能从第二级获取和打印。

这是我的完整代码,还有 json 模型:

import 'dart:async';
import 'dart:convert';

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

Future<List> fetchData(http.Client client) async {
  final response = await client
      .get('http://my-json-server.typicode.com/tariksalihovic/innbo/receipt');

  // Use the compute function to run parsePhotos in a separate isolate.
  return compute(parseData, response.body);
}

// A function that converts a response body into a List<Photo>.
List parseData(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map((json) => Receipt.fromJson(json)).toList();
}

class Lines {

  final String name;
  final String productNumber;

  Lines({this.name, this.productNumber});

  factory Lines.fromJson(Map<String, dynamic> json){
    return Lines(
        name: json['name'],
        productNumber:  json['productNumber']
    );

  }

}

class Receipt {
  final int id;
  final String type;
  final String receiptId;
  final String orderNumber;
  final List<Lines> receiptlines;

  Receipt({this.id, this.type, this.receiptId, this.orderNumber, this.receiptlines});

  factory Receipt.fromJson(Map<String, dynamic> json) {

    var list = json['receiptLines'] as List;
    print(list.runtimeType);
    List<Lines> receiptLines = list.map((i) => Lines.fromJson(i)).toList();

    return Receipt(
        id: json['id'],
      type: json['type'],
      receiptId: json['receiptId'],
      orderNumber: json['orderNumber'],
        receiptlines: receiptLines
    );
  }
  }


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Isolate Demo';

    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: FutureBuilder<List>(
        future: fetchData(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);

          return snapshot.hasData
              ? ReceiptList(data: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class ReceiptList extends StatelessWidget {
  final List data;

  ReceiptList({Key key, this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index) {
        return ListTile(
          leading: CircleAvatar(
            radius: 26,
            backgroundColor: Colors.grey[400],
            child: Icon(Icons.phone_iphone, color: Colors.white),
          ),
          title: Text(
            data[index].type,
            style: TextStyle(
                color: Colors.black,
                fontSize: 16.5,
                fontWeight: FontWeight.w700),
          ),
          subtitle: Text(
            data[index].receiptId,
            style: TextStyle(color: Colors.grey[700], fontSize: 12.0),
          ),
          trailing: Text(
            data[index].productName,
            style: TextStyle(
                color: Colors.black,
                fontSize: 16.5,
                fontWeight: FontWeight.w800),
          ),
        );
      },
    );
  }
}

【问题讨论】:

  • 模型类中没有productName字段。
  • 我的错,我提醒productNumber

标签: json flutter dart fetch


【解决方案1】:

在您的 Receipt.fromJson 中,将您当前的receiptLines 定义更改为:

List<Lines> receiptLines =
    List<Lines>.from(list.map((x) => Lines.fromJson(x))).toList();

然后,在您的尾随文本小部件中,您忘记在 productNumber 之前添加“receiptlines”,所以它应该是:

trailing: Text(
    data[index].receiptlines[index].productNumber,
    style: TextStyle(
        color: Colors.black,
        fontSize: 16.5,
        fontWeight: FontWeight.w800),
),

【讨论】:

  • 非常感谢!非常感谢!如果应该有更好的方法来获取嵌套的 json 数据或/和打印它而不是 data[index].receiptlines[index].string 我很想知道。
  • 没问题!很高兴我帮了忙。我敢肯定有办法简化下来。我也会看看,如果我找到了,我会告诉你。
  • 您好,谢谢。我偶然发现了另一个问题。我的解析器只遍历收据行的第一行,我添加了更多项目,例如Id: 1 有 3 个receiptLines,每个都包含一个name 和一个productNumber。它不是打印所有行,而是仅打印前 1 行,然后迭代到下一个 Id: 2 并再次打印其中的前 1 行。
  • 您打算如何显示您的收据行?
  • 在 SliverFixedExtentList 中使用 CustomScrollView - 在我的列表中,parrent json 数据将不可见,只有子 receiptLines id 的。当点击一个选项(例如receiptLine)时,我将为该项目提供neseccary parrent json数据。
猜你喜欢
  • 2020-10-06
  • 2020-10-19
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多