0
votes

I have a list of map in json and Im trying to render 'title' on a list.

Im reading data through through an api (http.get) then parse it.

I want to show the title in a list.

Here's my code...

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Getting the data

Future<Welcome> fetchAlbum() async {
  final response = await http.get('https://jsonplaceholder.typicode.com/posts');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Welcome.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');
  }
}

Convert to json

List<Welcome> welcomeFromJson(String str) =>
    List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

Model class Welcome

class Welcome {
  Welcome({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  int userId;
  int id;
  String title;
  String body;

  factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
      );

  Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "body": body,
      };
}

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

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

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

class _MyAppState extends State<MyApp> {
  Future<Welcome> 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: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Welcome>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return new Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

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

Im getting an error saying " type 'List' is not a subtype of type 'Map<String, dynamic>' "

1
Can you add a server response to the question? - fartem
It would be helpful if we could see the JSON response you're receiving - Stijn2210
What do you mean by JSON response? it's getting 200 - Kagimura
By JSON response we mean what you have got in response.body - Ali Alizadeh
do you want every post to be displayed or only 1 post - Sravan Kumar

1 Answers

1
votes

Change your fetchAlbum function to this

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

    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      // return Welcome.fromJson(jsonDecode(response.body));
      var jsonData = jsonDecode(response.body);
      List<Welcome> welcome = [];

      for (var v in jsonData) {
        Welcome w1 = Welcome(
            userId: v['userId'],
            id: v['id'],
            title: v['title'],
            body: v['body']);
        welcome.add(w1);
      }
      return welcome;
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }
  }

The FutureBuider widget will be this

child: FutureBuilder(
            future: fetchAlbum(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return Container(
                        margin: EdgeInsets.all(8),
                        child: Column(
                          children: [
                            Text("User Id = ${snapshot.data[index].userId}"),
                            Text("Id = ${snapshot.data[index].id}"),
                            Text("Title = ${snapshot.data[index].title}"),
                            Text("Body = ${snapshot.data[index].body}"),
                          ],
                        ),
                      );
                    });
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

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