解析复杂的JSON抖动

时间:2020-09-28 05:14:49

标签: json flutter dart

我正在尝试将复杂的json文件解析到我的应用程序中 我收到一个错误Exception: type 'String' is not a subtype of type 'int' in type cast。我不知道这发生在哪里以及如何解决

代码

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<Character>> fetchCharacters(http.Client client) async {
  final response =
  await client.get('http://swapi.dev/api/people/');
  // Use the compute function to run parsePhotos in a separate isolate.
  return compute(parseCharacter, response.body);
}

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

class Character {
  final String name;
  final int height;
  final int mass;
  final String hairColor;
  final String skinColor;
  Character({this.name, this.height, this.mass, this.hairColor, this.skinColor});
  factory Character.fromJson(Map<String, dynamic> json) {
    return Character(
      name: json['name'] as String,
      height: json['height'] as int,
      mass: json['mass'] as int,
      hairColor: json['hair_color'] as String,
      skinColor: json['skin_color'] as String,
    );
  }
}

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<Character>>(
        future: fetchCharacters(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? PhotosList(character: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Character> character;
  PhotosList({Key key, this.character}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: character.length,
      itemBuilder: (context, index) {
        return Card(
          elevation: 5,
          margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
          child: Container(
            padding: EdgeInsets.all(15),
            child: ListTile(
              title: Text(
                character[index].name,
                style: TextStyle(fontSize: 18, color: Colors.black),
              ),
              onTap: () {},
            ),
          ),
        );
      },
    );
  }
}

json文件

    "count": 82,
    "next": "http://swapi.dev/api/people/?page=2",
    "previous": null,
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue",
            "birth_year": "19BBY",
            "gender": "male",
            "homeworld": "http://swapi.dev/api/planets/1/",
            "films": [
                "http://swapi.dev/api/films/1/",
                "http://swapi.dev/api/films/2/",
                "http://swapi.dev/api/films/3/",
                "http://swapi.dev/api/films/6/"
            ],
            "species": [],
            "vehicles": [
                "http://swapi.dev/api/vehicles/14/",
                "http://swapi.dev/api/vehicles/30/"
            ],
            "starships": [
                "http://swapi.dev/api/starships/12/",
                "http://swapi.dev/api/starships/22/"
            ],
            "created": "2014-12-09T13:50:51.644000Z",
            "edited": "2014-12-20T21:17:56.891000Z",
            "url": "http://swapi.dev/api/people/1/"
        } 
   ]
} ```

1 个答案:

答案 0 :(得分:0)

只需删除在构造函数中添加的class AddWidget extends StatefulWidget { @override _AddWidgetState createState() => _AddWidgetState(); } class _AddWidgetState extends State<AddWidget> { List<Widget> containerList = []; Widget returnWidget() { return Padding( padding: const EdgeInsets.all(8.0), child: Container( width: double.infinity, height: 40, color: Colors.red, ), ); } @override Widget build(BuildContext context) { return Container( child: Column( children: [ Expanded( child: Container( color: Colors.yellow, height: 400, width: double.infinity, child: Column(children: containerList), ), ), RaisedButton( child: Text("Add"), onPressed: () { setState(() { containerList.add(returnWidget()); }); }, ) ], ), ); } } 并使用as intparseInt( json['mass'] )

parseInt( json['height'] )是dart中的一个函数,用于将int类型的数字字符串转换为可以在计算中使用的整数

也请检查此内容:https://dev.to/wangonya/how-you-turn-a-string-into-a-number-or-vice-versa-with-dart-392h