skip to Main Content

I want to receive data from an API and for that I created a SERVICE:

class ApiService {
  Future<List<dynamic>> getData() async {
    try {

      var response = await http.get(Uri.parse(Config.apiURL));
      debugPrint('Response code: ${response.statusCode}');
      if (response.statusCode == 200) {
        List<dynamic> data=jsonDecode(response.body) as List<dynamic>;
         debugPrint('in service:${data.toString()}');

        return data ;  
      }
      else{
      debugPrint('else');
      return [];
      }
    } catch (e) {
      throw Exception("Failed to fetch data..");
    }
  }
}

And I called him from StatefulWidget:

    void getData() async {
 
        debugPrint('entrance');
        userDataList= await ApiService().getData();
        debugPrint(userDataList.toString());  
  } 

    @override
  void initState() {
    debugPrint('init');
    super.initState();
    getData();
  }

And for some reason I am not receiving data.Would love your help.

2

Answers


  1. Check the Flutter devtool network inspector to see what is the response of your request. Also check that your device can well reach internet : no dns issue, proxy, vpn errors.

    If your method is call and never respond, maybe check the version of http used ? Old one ?

    To help you, i need more :

    • log
    • package version
    • flutter version
    • device used
    Login or Signup to reply.
  2. You can do this in more than one way, two of them can be:

    1) using setState in the Future

    class HomePage extends StatefulWidget {
      const HomePage({super.key});
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      List<dynamic> data = [];
    
      Future<void> presentData() async {
        await ApiService().getData().then((value) => setState(() {
              data = value;
            }));
      }
    
      @override
      void initState() {
        super.initState();
        presentData();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: data.isEmpty
              ? const Center(child: CircularProgressIndicator())
              : ListView.builder(
                  itemCount: data.length,
                  itemBuilder: (BuildContext context, int index) => ListTile(
                    title: Text('${data[index]}',
                        style: const TextStyle(color: Colors.black)),
                  ),
                ),
        );
      }
    }
    

    2) using StreamBuilder

    remembering that you are dealing with a streamController, so consider the dispose()

    class HomePage extends StatefulWidget {
      const HomePage({super.key});
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      StreamController<List<dynamic>> dataStreamController = StreamController();
    
      List<dynamic> data = [];
    
      Future<void> presentData() async {
        data = await ApiService().getData();
    
        dataStreamController.add(data);
      }
    
      @override
      void initState() {
        super.initState();
        presentData();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: StreamBuilder<List<dynamic>>(
            stream: dataStreamController.stream,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text('${snapshot.data![index]}',
                          style: const TextStyle(color: Colors.black)),
                    );
                  },
                );
              } else {
                return const Center(child: CircularProgressIndicator());
              }
            },
          ),
        );
      }
    
      @override
      void dispose() {
        dataStreamController.close();
        super.dispose();
      }
    }
    

    ApiService class:

    class ApiService {
      Future<List<dynamic>> getData() async {
        List data = [];
        try {
          var response = await http
              .get(Uri.parse(config.apiUrl));
          debugPrint('Response code: ${response.statusCode}');
          if (response.statusCode == 200) {
            try {
              data = (jsonDecode(response.body))
                  .map((e) => e as Map<String, dynamic>)
                  .toList();
    
              return data;
            } catch (err) {
              print(err);
              return [];
            }
          } else {
            debugPrint('else');
            return [];
          }
        } catch (e) {
          throw Exception('Failed to fetch data..');
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search