Home > Net >  Create a Flutter Application using API
Create a Flutter Application using API

Time:01-12

I'm new to Flutter and I'm trying to create an application with a ListView using this API: https://metmuseum.github.io/#search. Here is my code:

main.dart

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

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

Now I'm having problems because the ListView is not created and gives me errors. Could you check the code and make sure everything is right? I think the problem comes from the getUsers() class, where I try to get the API data.

CodePudding user response:

In your user.dart file, you need a fromJson method but it takes a map<String,dynamic> instead of a 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']);
}

And in your main file

You can create your instance of user like this :

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

and finally uncomment your code in the build method

  • Related