Flutter : Api 显示数据形式 json

Flutter : Api display Data form json

我想将 api 数据显示为列表并添加一个带 onTap 的 Inkwell,每次用户单击一个项目时,数据都会显示在另一个 class 中,但我得到了一个主飞镖中第 42 行的错误错误

列表 resData = snapshot.data;

代码仅加载但不显示 api 中的任何内容。

我用api专辑形式flutter

主要

    import 'dart:async';
import 'package:flutter/material.dart';
import 'data/functions.dart';
import 'album.dart';



void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
            List resData = snapshot.data;
            return ListView.builder(
                itemCount: resData.length,
                itemBuilder: (context, index) {
                   return Card(
                     child: ListTile(title: Text(resData[index]["title"]),),
                   );
                   
                });
          }

              // if (snapshot.hasData) {
              //   return Text(snapshot.data!.title);
              // } else if (snapshot.hasError) {
              //   return Text('${snapshot.error}');
              // }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

飞镖函数

import 'dart:convert';
import 'package:gamess/album.dart';
import 'package:http/http.dart' as http;

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

专辑飞镖



class Album {
  final int userId;
  final int id;
  final String title;

  Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

好的,首先您从 API 收到一个相册列表,并且您正在尝试使用 fromJson 将一个相册列表解析为一个相册。要解决此问题,请将代码从 functions.dart 更改为此。

`

import 'dart:convert';
import '../album.dart';
import 'package:http/http.dart' as http;

Future<List<Album>> fetchAlbum() async {
  final response =
      await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.

    List<Album> albums = [];

    List<dynamic> albumsJson = jsonDecode(response.body);

    albumsJson.forEach(
      (oneAlbum) {
        Album album = Album.fromJson(oneAlbum);
        albums.add(album);
      },
    );

    return albums;
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

`

第二件事是现在您正在正确接收数据让我们修复 ui,您不能在没有 await 的情况下调用 Future 并且您不能在 init 上调用 await,因此删除了 late Future<Album> futureAlbum;futureAlbum = fetchAlbum();;

接下来,您必须调整对未来 builder 的未来调用,将 future: futureAlbum, 更改为 future: fetchAlbum(),;

现在您知道您正在接收一个列表,您必须在 Future builder 上定义它。

有问题尽管问,main.dart文件如下:

`

import 'package:flutter/material.dart';
import 'data/functions.dart';
import 'album.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<List<Album>>(
            future: fetchAlbum(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<Album>? resData = snapshot.data;
                return ListView.builder(
                    itemCount: resData != null ? resData.length : 0,
                    itemBuilder: (context, index) {
                      return Card(
                        child: ListTile(
                          title: Text(resData?[index].title ?? ""),
                        ),
                      );
                    });
              }

              // if (snapshot.hasData) {
              //   return Text(snapshot.data!.title);
              // } else if (snapshot.hasError) {
              //   return Text('${snapshot.error}');
              // }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

`