【问题标题】:Flutter : Api display Data form jsonFlutter : Api 显示数据形式 json
【发布时间】:2021-12-15 03:21:36
【问题描述】:

我想将 api 数据显示为列表并添加一个带有 onTap 的 Inkwell,其中每次用户单击一个项目时,数据都会显示在另一个类中,但我在 main dart 的第 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'],
    );
  }
}

【问题讨论】:

    标签: json flutter dart listview


    【解决方案1】:

    好的,首先您从 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&lt;Album&gt; futureAlbum; 和 @987654324 @;

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

    既然您知道您正在接收一个列表,您必须在 Future 构建器上定义它。

    任何问题都可以问,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();
                },
              ),
            ),
          ),
        );
      }
    }
    

    `

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-17
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2022-01-13
      • 2022-10-04
      • 2021-06-20
      相关资源
      最近更新 更多