简体   繁体   English

Flutter:Api 显示数据表单 json

[英]Flutter : Api display Data form json

I want to display the api data as a list and add an Inkwell with onTap where every time the user clicks on an item, data is displayed in another class, but I get an error at line 42 in main dart the error我想将 api 数据显示为列表并添加一个带有 onTap 的 Inkwell,每次用户单击一个项目时,数据都会显示在另一个类中,但是我在 main dart 的第 42 行出现错误

List resData = snapshot.data;列表 resData = snapshot.data;

The code just loads but doesn't display anything from the api.代码只是加载但不显示 api 中的任何内容。

I use api album form flutter我使用 api 专辑形式 flutter

the main主要的

    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();
            },
          ),
        ),
      ),
    );
  }
}

The functions dart函数飞镖

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');
  }
}

the album dart专辑飞镖



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'],
    );
  }
}

Ok, first you recieve from API a list of Albums and you are trying to parse a list of Albums into a single Album with the fromJson.好的,首先您从 API 接收专辑列表,然后尝试使用 fromJson 将专辑列表解析为单个专辑。 To fix this, change the code from functions.dart to this.要解决此问题,请将代码从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');
  }
}

` `

Second thing is now that you are receiving the data properly lets fix the ui, you can't call a Future without await and you can't call a await on init, so a removed the late Future<Album> futureAlbum;第二件事是现在您正在正确接收数据,让我们修复 ui,您不能在没有 await 的情况下调用 Future,也不能在 init 上调用 await,因此删除了late Future<Album> futureAlbum; and the futureAlbum = fetchAlbum();futureAlbum = fetchAlbum(); ; ;

Next you have to adapt the future call on the future builder, changing the future: futureAlbum, to future: fetchAlbum(), ;接下来你必须适应未来构建器的未来调用,改变future: futureAlbum,future: fetchAlbum(),

Now that you know you're receiving a List you have to define that on the Future builder.现在您知道您正在接收一个列表,您必须在 Future 构建器上定义它。

Any questions just ask, the main.dart file is below:任何问题都可以问, 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();
            },
          ),
        ),
      ),
    );
  }
}

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM