I am developing an app with the help of spoonacular API. I want to access the reciepeList
list variable in the main.dart so that I can implement it in the UI. But while doing that its giving me an empty list. But within the function its running properly.
This is my services.dart:-
import 'dart:convert';
import 'package:http/http.dart';
import 'package:spponacular/reciepe.dart';
class GetRecipies{
final dynamic api='9c9a158fced340a1873d5988704968c2';
List<Reciepes>reciepeList=[];
Future getReciepe() async{
try{
// make the request
Response response = await get(Uri.parse('https://api.spoonacular.com/recipes/findByNutrients?apiKey=$api&minCalories=50&maxCalories=700&number=7'));
List data = jsonDecode(response.body);
reciepeList=data.map((e) {
return Reciepes(name:"${e['title']}", image: "${e['image']}", calories: "${e['calories']}", carbs: "${e['carbs']}", fat: "${e['fat']}", protein: "${e['protein']}");}).toList();
print(reciepeList[0].name);
print(reciepeList);
}
catch (e) {
print(e);
}
}
}
If I try to print the reciepieList
within the function I am getting the right output.
But if I try to access the list through an object in the main.dart the list is empty. The output of the recipieList
length is showing 0. How to fix this?? And why am I getting this problem?
This is my main.dart file:
import 'package:flutter/material.dart';
import 'package:spponacular/services.dart';
void main() {
runApp(MaterialApp(
home: Home(),
));
}
class Home extends StatefulWidget {
const Home({ Key? key }) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
void initState() {
super.initState();
GetRecipies obj=GetRecipies();
print(obj.reciepeList.length);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepPurpleAccent,
title: Text('Recipes'),
),
body: ListView.builder(
itemBuilder: (context,index){
return Container(
);
}),
);
}
}