类型“ _InternalLinkedHashMap”不是类型的子类型

时间:2020-03-14 21:15:46

标签: flutter

我试图使用http请求传递json数据以显示列表,当我点击列表之一时,出现此错误:类型'_InternalLinkedHashMap'不是类型'Todo'的子类型

我需要的是在下一个屏幕的中央显示标题。

我是新手,请帮助...

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

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

void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {

  List data;

  Future<String> getData() async {
    var response = await http.get(
      Uri.encodeFull("https://jsonplaceholder.typicode.com/posts"),
      headers: {
        "Accept": "application/json"
      }
    );

    this.setState(() {
      data = jsonDecode(response.body);
    });
    print(data[1]["title"]);

    return "Success!";
  }

  @override
  void initState() {
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Listviews"),
      ),
      body: new ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
                    Navigator.push(context, 
                    new MaterialPageRoute(builder: (context) => DetailsPage(todo: data[index]))
                    );
                                    },
                      child: new Card(
              child: new Text(data[index]["title"]),
            ),
          );
        },
      ),
    );
  }
}

class Todo {
  final String title;
  Todo(this.title);
}


class DetailsPage extends StatelessWidget {
  final Todo todo;
   DetailsPage({Key key, @required this.todo}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: new AppBar(
        title: new Text("Listviews"),
      ),

      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Text("todo.title"),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以在下面复制粘贴运行完整代码
您可以使用todoFromJson来解析json字符串
代码段

List<Todo> todoFromJson(String str) =>
    List<Todo>.from(json.decode(str).map((x) => Todo.fromJson(x)));
...
setState(() {
  data = todoFromJson(response.body);
});

工作演示

enter image description here

完整代码

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

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
//     final todo = todoFromJson(jsonString);

import 'dart:convert';

List<Todo> todoFromJson(String str) =>
    List<Todo>.from(json.decode(str).map((x) => Todo.fromJson(x)));

String todoToJson(List<Todo> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Todo {
  int userId;
  int id;
  String title;
  String body;

  Todo({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  factory Todo.fromJson(Map<String, dynamic> json) => Todo(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
      );

  Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "body": body,
      };
}

void main() {
  runApp(MaterialApp(
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  List<Todo> data;

  Future<String> getData() async {
    var response = await http.get(
        Uri.encodeFull("https://jsonplaceholder.typicode.com/posts"),
        headers: {"Accept": "application/json"});

    setState(() {
      data = todoFromJson(response.body);
    });

    return "Success!";
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Listviews"),
      ),
      body: ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => DetailsPage(todo: data[index])));
            },
            child: Card(
              child: Text(data[index].title),
            ),
          );
        },
      ),
    );
  }
}

class DetailsPage extends StatelessWidget {
  final Todo todo;
  DetailsPage({Key key, @required this.todo}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Listviews"),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Text("${todo.title}"),
      ),
    );
  }
}