使用API创建Flutter应用程序

u3r8eeie  于 2023-01-14  发布在  Flutter
关注(0)|答案(1)|浏览(124)

我是Flutter的新手,我正在尝试使用以下API创建一个包含ListView的应用程序:www.example.com。下面是我的代码:https://metmuseum.github.io/#search. Here is my code:

    • 主省道**
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'user.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MET',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<List<User>> usersFuture = getUsers();

  static Future<List<User>> getUsers() async {
    var body;
    for (int i = 0; i < 5; i++) {
      String url =
          'https://collectionapi.metmuseum.org/public/collection/v1/objects/$i';
      var response = await http.get(Uri.parse(url));
      body = json.decode(response.body);
    }

    return body.map<User>(User.fromJson).toList();
  }

  

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: const Text("Metropolitan Museum of Art"),
          centerTitle: true,
        ),
        body: Center(
          child: FutureBuilder<List<User>>(
            future: usersFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              } /*else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                final users = snapshot.data!;
                return buildUsers(users);
              }*/
              final users = snapshot.data!;
                return buildUsers(users);
            },
          ),
        ),
      );

  Widget buildUsers(List<User> users) => ListView.builder(
        itemCount: users.length,
        itemBuilder: (context, index) {
          final user = users[index];

          return Card(
            child: ListTile(
              leading: CircleAvatar(
                radius: 28,
                backgroundImage: NetworkImage(user.primaryImageSmall),
              ),
              title: Text(user.title),
              subtitle: Text(user.artistDisplayName),
            ),
          );
        },
      );
}
    • 用户. dart**
import 'package:flutter/material.dart';

class User {
  final int objectID;
  final bool isHighlight;
  final String accessionYear;
  final String primaryImage;
  final String primaryImageSmall;
  final String department;
  final String objectName;
  final String title;
  final String culture;
  final String period;
  final String artistPrefix; //da usare prima dell'artista
  final String artistDisplayName;
  final String artistDisplayBio;
  final String medium; //Refers to the materials that were used to create the artwork
  final String dimensions;
  final String geographyType; //da usare prima della città in cui è stata fatta l'opera
  final String city;
  final String state;
  final String classification;
  final String linkResource;
  final String GalleryNumber;

  const User(
      {required this.objectID,
      required this.isHighlight,
      required this.accessionYear,
      required this.primaryImage,
      required this.primaryImageSmall,
      required this.department,
      required this.objectName,
      required this.title,
      required this.culture,
      required this.period,
      required this.artistPrefix,
      required this.artistDisplayName,
      required this.artistDisplayBio,
      required this.medium,
      required this.dimensions,
      required this.geographyType,
      required this.city,
      required this.state,
      required this.classification,
      required this.linkResource,
      required this.GalleryNumber});

  static User fromJson(json) => User(
      objectID: json['objectID'],
      isHighlight: json['isHighlight'],
      accessionYear: json['accessionYear'],
      primaryImage: json['primaryImage'],
      primaryImageSmall: json['primaryImageSmall'],
      department: json['department'],
      objectName: json['objectName'],
      title: json['title'],
      culture: json['culture'],
      period: json['period'],
      artistPrefix: json['artistPrefix'],
      artistDisplayName: json['artistDisplayName'],
      artistDisplayBio: json['artistDisplayBio'],
      medium: json['medium'],
      dimensions: json['dimensions'],
      geographyType: json['geographyType'],
      city: json['city'],
      state: json['state'],
      classification: json['classification'],
      linkResource: json['linkResource'],
      GalleryNumber: json['GalleryNumber']);
}

现在我遇到了一些问题,因为ListView没有创建,并给我错误。你能检查代码并确保一切都正确吗?我认为问题来自getUsers()类,我试图在那里获得API数据。

slhcrj9b

slhcrj9b1#

在user.dart文件中,您需要一个fromJson方法,但它使用map〈String,dynamic〉而不是json

static User fromJson(Map<String, dynamic> json) => User(
      objectID: json['objectID'],
      isHighlight: json['isHighlight'],
      accessionYear: json['accessionYear'],
      primaryImage: json['primaryImage'],
      primaryImageSmall: json['primaryImageSmall'],
      department: json['department'],
      objectName: json['objectName'],
      title: json['title'],
      culture: json['culture'],
      period: json['period'],
      artistPrefix: json['artistPrefix'],
      artistDisplayName: json['artistDisplayName'],
      artistDisplayBio: json['artistDisplayBio'],
      medium: json['medium'],
      dimensions: json['dimensions'],
      geographyType: json['geographyType'],
      city: json['city'],
      state: json['state'],
      classification: json['classification'],
      linkResource: json['linkResource'],
      GalleryNumber: json['GalleryNumber']);
}

在你的主文件里
您可以按如下方式创建用户示例:

static Future<List<User>> getUsers() async {
    var body;
    List<User> usersList = [];
    for (int i = 1; i < 5; i++) {
      String url =
          'https://collectionapi.metmuseum.org/public/collection/v1/objects/$i';
      var response = await http.get(Uri.parse(url));
      body = json.decode(response.body);
      usersList.add(User.fromJson(body));
    }
    return usersList;
  }

最后取消build方法中代码的注解

相关问题