为什么DataTable在Flutter中不显示JSON

时间:2019-05-22 23:05:34

标签: flutter

我正在通过 json 调用构建 DataTable 。一切进展顺利,但数据未显示。

//standing.dart
import '../modal/catelog_point_table_model.dart';
import '../services/category_point_table_services.dart';
import 'package:flutter/material.dart';

class DataTableWidget extends StatefulWidget {
  @override
  DataTableWidgetState createState() => DataTableWidgetState();
}

class DataTableWidgetState extends State<DataTableWidget> {
  final List<String> cityColumns = [
    'Team',
    'M',
    'W',
    'NRR',
    'Pts'
  ];
  List<City> cities;
  bool ascending;

  @override
  void initState() {
    super.initState();
    ascending = false;
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: SizedBox(
        width: width*1.5,
        child: ListView(
          children: <Widget>[
            buildDataTable(),
          ],
        ),
      ),
    );
  }

  Widget buildDataTable() => DataTable(
    sortAscending: ascending,
    columns: cityColumns
        .map(
          (String column) => DataColumn(
        label: Text(column),
        onSort: (int columnIndex, bool ascending) => onSortColumn(
            columnIndex: columnIndex, ascending: ascending),
      ),
    )
        .toList(),
    rows: cities.map((City city) => DataRow(
        cells: [
          DataCell(Text('${city.title}')),
          DataCell(Text('${city.price}')),
          DataCell(Text('${city.description}')),
          DataCell(Text('${city.nrr}')),
          DataCell(Text('${city.pts}')),
        ],
    ))
        .toList(),
  );

  void onSortColumn({int columnIndex, bool ascending}) {
    if (columnIndex == 0) {
      setState(() {
        if (ascending) {
          cities.sort((a, b) => a.title.compareTo(b.title));
        } else {
          cities.sort((a, b) => b.title.compareTo(a.title));
        }
        this.ascending = ascending;
      });
    }
  }
}


//catelog_point_table_model.dart

import 'dart:async' show Future;
import '../modal/catelog_point_table_model.dart';
import 'package:http/http.dart' as http;
import 'dart:async';

Future<List<City>> loadCatelog(String id) async {
  String url = 'https://icc-point-table.nittodigital.now.sh/api/Catelogs/category/5ce1a425eda9891fa8b51430';
  final response = await http.get(url);
  print(response.body);
  return cities(response.body);
}

//catelog_point_table_model.dart
import 'dart:convert';

class City {
  final int imgcount;
  final String id;
  final String title;
  final String price;
  final String description;
  final String nrr;
  final String pts;
  final List<String> gallery;

  City({
    this.imgcount,
    this.id,
    this.title,
    this.price,
    this.description,
    this.nrr,
    this.pts,
    this.gallery
  });

  factory City.fromJson(Map<String, dynamic> parsedJson) {
    var streetsFromJson  = parsedJson['gallery'];
    //print(streetsFromJson.runtimeType);
    // List<String> streetsList = new List<String>.from(streetsFromJson);
    List<String> galleryList = streetsFromJson.cast<String>();

    return new City(
      imgcount: parsedJson['img_v'],
      id: parsedJson['_id'],
      title: parsedJson['title'],
      price: parsedJson['price'],
      description: parsedJson['description'],
      nrr: parsedJson['nrr'],
      pts: parsedJson['pts'],
      gallery: galleryList,
    );
  }

}
List<City> cities(str) {
    final jsonData = json.decode(str);
    return List<City>.from(jsonData.map((x) => City.fromJson(x)));
}

NoSuchMethodError:方法'map'在null上调用

这就是我得到的。也许我没有获取数据,因为List不是静态类型。 如果有人告诉我如何正确获取数据并与DataRow建立联系,那就太好了。 *对不起,我英语不好。

1 个答案:

答案 0 :(得分:0)

您必须从loadCatelog函数内部调用initState。由于您的调用是异步的,并且initState不允许异步调用,因此您必须将代码放在单独的方法中:

@override
  void initState() {
    super.initState();
    ascending = false;
    _getData();
}

void _getData() async{
    cities = await loadCatelog();
}

此外,您还要求将id作为函数的参数,但不要使用它。因此,请删除该参数或相应地传递它。

如果您只需要从API检索一次数据,或者如果您要从所述API获得实时更新,FutureBuilder,则使用StreamBuilder会是一种更优雅的方法。