Search code examples
flutterapirestdartdio

flutter does not show data from API


When I try to pull data from the jsonplaceholder API and put it on the screen, I don't have any problems, but when I try to change the data in this link (https://reqres.in/api/users?page=2 ) on the reqres.io site with the same codes, only by changing the API and model, the text no data appears on the screen. I'm getting it can you help me ?

My project with JsonPlaceHolder

main.dart

import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';

import 'service/api_service.dart';

void main() =\> runApp(const MyApp());

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

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}

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

@override
State\<Home\> createState() =\> \_HomeState();
}

class \_HomeState extends State\<Home\> {
List\<JsonModel\>? \_postItems;
bool \_isLoading = false;
String? \_errorMessage;

@override
void initState() {
super.initState();
loadData();
}

Future\<void\> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}

@override
Widget build(BuildContext context) {
if (\_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (\_postItems == null || \_postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: \_postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].name),
);
},
);
}
}
}`

api_service.dart

`import 'dart:io';

import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';

class Api {
static Future<List<JsonModel>?> fetchApi() async {
final res = await Dio().get("https://jsonplaceholder.typicode.com/users");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!;
if (data is List) {
return data.map((e) =\> JsonModel.fromMap(e)).toList();
}
}
return <JsonModel>[];
}
}
`

conclusion

conclusion

My project with reqres.in

main.dart

`import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';

import 'service/api_service.dart'; 

void main() =\> runApp(const MyApp());

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

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}

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

@override
State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
List<ReqresModel>? _postItems;
bool _isLoading = false;
String? _errorMessage;

@override
void initState() {
super.initState();
loadData();
}

Future<void> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
}); 
}
}

@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (_postItems == null || _postItems!.isEmpty) { 
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: _postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].data\[index\].firstName),
);
},
);
}
}
}`

api_servise.dart

`import 'dart:io';

 import 'package:my_app/models/json_model.dart';
 import 'package:dio/dio.dart';

 class Api {
 static Future<List<ReqresModel>?> fetchApi() async {
 final res = await Dio().get("https://reqres.in/api/users?page=2");
 if (res.statusCode == HttpStatus.ok) {
 final data = res.data!;
 if (data is List) {
 return data.map((e) => ReqresModel.fromMap(e)).toList();
 }
 }
 return <ReqresModel>[];
 }
 }`

conclusion

conclusion

**Thank you **

I sent the API using Postman, there was no problem, I don't think the problem was caused by the API, sorry for my bad English


Solution

  • Change your api_service.dart for reqres.in project with following code. First api which returns List directly, but second api which return Json which has data as List

    Edited

    main.dart

    import 'package:flutter/material.dart';
    import 'package:my_app/models/json_model.dart';
    
    import 'service/api_service.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Material App',
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Json Deneme'),
            ),
            body: const Home(),
          ),
        );
      }
    }
    
    class Home extends StatefulWidget {
      const Home({super.key});
    
      @override
      State<Home> createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      List<ReqresModel>? _postItems;
      bool _isLoading = false;
      String? _errorMessage;
    
      @override
      void initState() {
        super.initState();
        loadData();
      }
    
      Future<void> loadData() async {
        setState(() {
          _isLoading = true;
          _errorMessage = null;
        });
        try {
          final postItems = await Api.fetchApi();
          setState(() {
            _postItems = postItems;
            _isLoading = false;
          });
        } catch (e) {
          setState(() {
            _isLoading = false;
            _errorMessage = 'Error fetching data: $e';
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        if (_isLoading) {
          return const Center(child: CircularProgressIndicator());
        } else if (_postItems == null || _postItems!.isEmpty) {
          return const Center(child: Text('No Data'));
        } else {
          return ListView.builder(
            itemCount: _postItems!.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(_postItems![index].firstName),//Updated here
              );
            },
          );
        }
      }
    }
    

    api_service.dart

    import 'dart:io';
    
    import 'package:my_app/models/json_model.dart';
    import 'package:dio/dio.dart';
    
    class Api {
      static Future<List<ReqresModel>?> fetchApi() async {
        final res = await Dio().get("https://reqres.in/api/users?page=2");
        if (res.statusCode == HttpStatus.ok) {
          final data = res.data!['data'];//Updated here
          if (data is List) {
            return data.map((e) => ReqresModel.fromMap(e)).toList();
          }
        }
        return <ReqresModel>[];
      }
    }
    

    ReqresModel - should be updated

    //Updated here
    class ReqresModel {
      int? id;
      String? email;
      String? firstName;
      String? lastName;
      String? avatar;
    
      ReqresModel(
          {this.id, this.email, this.firstName, this.lastName, this.avatar});
    
      ReqresModel.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        email = json['email'];
        firstName = json['first_name'];
        lastName = json['last_name'];
        avatar = json['avatar'];
      }
    }