I'm trying to get the user's currency from my server. Until now I'm able to do that but the problem is the data keeps rebuild itself everytime the app gets rebuilt. I tried to fix that by this way :
Future<dynamic> userDataFuture;
ApiService apiService;
@override
void initState() {
userDataFuture = apiService.getUserData();
super.initState();
}
but fails as it gives me an error saying :
The method 'getUserData' was called on null. Receiver: null Tried calling: getUserData()
this is my ApiService Class
Future getUserData() async {
String token = await AuthProvider().getToken();
String userID = await AuthProvider().getUserId();
final response = await Dio().get(
'$apiUrl/$userID',
options: Options(headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
}),
);
if (response.statusCode == 200) {
return response.data;
} else {
throw Exception('Failed to load data');
}
}
this is my UI where I want to show the user's currency:
child: Center(
child: FutureBuilder(
future: userDataFuture,
builder:
(BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
"Something wrong with message: ${snapshot.error.toString()}"),
);
} else if (snapshot.connectionState ==
ConnectionState.done) {
return Text(
snapshot.data[
'currency'], // This Should Change Depending in Settings of the User
style: TextStyle(
fontSize:
(device.localWidth * .1) * .43,
fontWeight: FontWeight.w500,
color: kLightTextColor));
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
// ),
),
),