我正在尝试解决一个问题,无法通过谷歌搜索或在此处找到任何答案,所以这是我的问题。
我正在尝试从自己的json测试服务器中获取json数据:http://my-json-server.typicode.com/tariksalihovic/innbo/receipt
json数据是嵌套的,我正在尝试获取jsont_code的信息,我已经按照嵌套json数据的教程进行操作,但是无法解决如何从ReceivingLine打印"receiptLines":字符串的问题。
至于我的代码,我尝试使用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),
          ),
        );
      },
    );
  }
}

最佳答案

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

List<Lines> receiptLines =
    List<Lines>.from(list.map((x) => Lines.fromJson(x))).toList();
然后,在尾随的文本小部件中,您忘记在productNumber之前添加“收据”,因此应为:
trailing: Text(
    data[index].receiptlines[index].productNumber,
    style: TextStyle(
        color: Colors.black,
        fontSize: 16.5,
        fontWeight: FontWeight.w800),
),
json - 类没有实例 getter -JSON模型-LMLPHP

关于json - 类没有实例 getter -JSON模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64270769/

10-10 18:03