Home > Mobile >  Why Does my code return circularprogressindicator always, it is not fetching my data
Why Does my code return circularprogressindicator always, it is not fetching my data

Time:10-30

When i run the application it doesnt fetch the data

import 'package:fakeapi/homepage.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:fakeapi/album.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:http/http.dart' as http;

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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.lightGreen,
      ),
      home: const HomePage(),
    );
  }
}



class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        builder: ((context, snapshot) {
          if (snapshot.hasError) {
            throw Exception("ERROR");
          } else if (snapshot.hasData) {
            ListView.builder(
              itemBuilder: ((context, index) {
                return Text(snapshot.data!.title);
              }),
              itemCount: 1,
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        }),
        future: getAlbums(),
      ),
    );
  }
}

Future<Album> getAlbums() async {
  final response = await http
      .get(Uri.parse("https://jsonplaceholder.typicode.com/albums/10"));
  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception("hey");
  }
}

// To parse this JSON data, do
//
//     final album = albumFromJson(jsonString);



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

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




This is how i coded my class



class Album {
  Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  int userId;
  int id;
  String title;

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

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


I tried to fetch data and display it

import 'package:fakeapi/homepage.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:fakeapi/album.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:http/http.dart' as http;

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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.lightGreen,
      ),
      home: const HomePage(),
    );
  }
}



class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        builder: ((context, snapshot) {
          if (snapshot.hasError) {
            throw Exception("ERROR");
          } else if (snapshot.hasData) {
            ListView.builder(
              itemBuilder: ((context, index) {
                return Text(snapshot.data!.title);
              }),
              itemCount: 1,
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        }),
        future: getAlbums(),
      ),
    );
  }
}

Future<Album> getAlbums() async {
  final response = await http
      .get(Uri.parse("https://jsonplaceholder.typicode.com/albums/10"));
  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception("hey");
  }
}

// To parse this JSON data, do
//
//     final album = albumFromJson(jsonString);



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

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

class Album {
  Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  int userId;
  int id;
  String title;

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

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

CodePudding user response:

How do you know it doesn't fetch the data? With your current code you always return the CircularProgressIndicator when there isn't an error.

You have to return the ListView builder. I.e.

return ListView.builder(
              itemBuilder: ((context, index) {
                return Text(snapshot.data!.title);
              }),
              itemCount: 1,
            );

CodePudding user response:

Your current api return a single model,

.....typicode.com/albums/10" 

You wont get a list here. You can return single item from this like changing ListView to Text.

if (snapshot.hasData) {
  return Text("${snapshot.data?.title}");

You can follow this widget to receive full list

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late final future = getAlbums();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Album>?>(
          future: future,
          builder: (context, snapshot) {
            print(snapshot);
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data?.length,
                itemBuilder: ((context, index) {
                  final model = snapshot.data![index];
                  return Text("${model.title}");
                }),
              );
            }
            return Center(
              child: CircularProgressIndicator(),
            );
          }),
    );
  }
}

Future<List<Album>?> getAlbums() async {
  final response =
      await http.get(Uri.parse("https://jsonplaceholder.typicode.com/albums/"));
  if (response.statusCode == 200) {
    final data = jsonDecode(response.body) as List?;

    return data?.map((e) => Album.fromJson(e)).toList();
  } else {
    throw Exception("hey");
  }
}

CodePudding user response:

change your FutureBuilder to this:

builder: ((context, snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.waiting:
        return Center(
            child: CircularProgressIndicator(),
          );
      default:
        if (snapshot.hasError) {
          throw Exception("ERROR");
        } else {
          return ListView.builder(
               itemBuilder: ((context, index) {
                   return Text(snapshot.data!.title);
               }),
               itemCount: 1,
          );
        }
    }
}),
  • Related