提问者:小点点

错误:类型“列表<动态>”不是类型“列表<数据行>”的子类型


我想以表格式显示数据,我试图以数据表格式显示其余api数据并收到错误:。

以下_TypeError被抛出构建FutureBuilder

(包:flutter_app_network_call/main. dart:68:14)#1_FutureBuilderState.build(包:flutter/src/widget/async.dart:775:55)#2StatefulElement.build(包:flutter/src/widget/frame.dart:4691:27)#3 ComponentElement.performRebuild(包:flutter/src/widget/frame.dart:4574:15)#4 StatefulElement.performRebuild(包:flutter/src/widget/frame.dart:4746:11)…

═════════════════════════════════════════════

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
void main() => runApp(MaterialApp(
    home: MyApp(),
));

class MyApp extends StatefulWidget {

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  Future<List<Post>> getPost() async{
    var data = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
    var jsonData = json.decode(data.body);

    List<Post> posts = [];

    for (var _post in jsonData){
      Post post = Post(_post['id'], _post['userId'], _post['title'], _post['body']);
      posts.add(post);
    }

    print(posts.length);
    return posts;

  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
        future: getPost(),
        builder: (BuildContext context, AsyncSnapshot snapshot){

          if(snapshot.data == null){
              return Container(
                child: Center(
                  child: Text('Loading...'),
                ),
              );
          }else{
            for(var pst in snapshot.data){
              print(pst.body);
            }
            return DataTable(
                columns: [
                  DataColumn(label: Text('Id')),
                  DataColumn(label: Text('Body'))
                ],
                rows: snapshot.data
                .map(
                (data) => DataRow(
                cells: [
                  DataCell(
                    Text(data.id.toString()),
                  ),
                  DataCell(
                    Text(data.body),
                  )
                ]),
          ) .toList(),
            );
          }
        },
      ),
    );
  }
}


class Post{
  final int id;
  final int userId;
  final String title;
  final String body;

  Post(this.id, this.userId, this.title, this.body);
}

共1个答案

匿名用户

指定map的类型为map

    return DataTable(
      columns: [DataColumn(label: Text('Id')), DataColumn(label: Text('Body'))],
      rows: snapshot.data
          .map<DataRow>(
            (data) => DataRow(cells: [
              DataCell(
                Text(data.id.toString()),
              ),
              DataCell(
                Text(data.body),
              )
            ]),
          )
          .toList(),
    );