I'm trying to get data every 30 seconds but I don't understand how to do it. There is no problem with the Getx controller file I created. I am able to pull the data but it is not refreshing.
This is my controller:
class AllCoinController extends GetxController {
var coinList = [].obs;
var coinCounter = 0.obs;
Future callAllCoins() async {
try {
final response = await http.get(url);
if (response.statusCode == 200) {
List<dynamic> values = [];
values = allCoinsFromJson(response.body);
coinCounter.value = values.length;
if (values.length > 0) {
for (int i = 0; i < values.length; i++) {
if (values[i] != null) {
coinList.add(values[i]);
}
}
}
return coinList;
} else {
print(response.statusCode);
}
} catch (e) {
print(e.toString());
}
}
@override
void onInit() {
callAllCoins();
Timer.periodic(Duration(seconds: 30), (timer) => callAllCoins());
super.onInit();
}
}
And my Homepage:
class HomePage extends StatelessWidget {
final AllCoinController allCoinController = Get.put(AllCoinController());
@override
Widget build(BuildContext context) {
return Scaffold(
body: Obx(
() => ListView.builder(
scrollDirection: Axis.vertical,
itemCount: allCoinController.coinCounter.value,
itemBuilder: (context, index) {
return Container(
width: 150,
child: Row(
children: [
SizedBox(
width: 50,
height: 50,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.network(
allCoinController.coinList[index].image),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(allCoinController.coinList[index].name),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(allCoinController.coinList[index].symbol),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Obx(
() => Text(allCoinController.coinList[index].currentPrice
.toString()),
),
),
],
),
);
},
),
),
);
}
}
There is no problem with the codes, the only problem is the timer is not working.