I am creating an app with getx. I have simple GET requests and i show the data to screen. In the detail screen, I put a button to refresh the request, response of request is coming randomly so everytime user pushes the button a different text will be shown. I did not figured out how to do that.
My Controller:
class JokeController extends GetxController {
var isLoading = true.obs;
var joke = Joke().obs;
@override
void onInit() {
fetchJoke();
super.onInit();
}
void fetchJoke() async {
isLoading(true);
try {
var chosenCategory = GetStorage().read("chosenCategory");
var _joke = await Requests.getJoke(chosenCategory);
if (_joke != null) {
joke.value = _joke;
}
} finally {
isLoading(false);
}
}
}
My Request:
static Future<Joke> getJoke(String chosenCategory) async {
try {
var response =
await client.get(Uri.parse(url)).timeout(Duration(seconds: 10));
if (response.statusCode == 200) {
Joke _joke = new Joke();
var responseBody = response.body;
return _joke.jokeFromJson(responseBody);
}
} catch (error) {
return null;
}
}
In Page (Obx):
Obx(() {
if (jokeController.isLoading.value) {
return Center(
child: CircularProgressIndicator().reactive(),
);
}
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Padding(
padding: EdgeInsets.only(
right: MediaQuery.of(context).size.width * .1,
left: MediaQuery.of(context).size.width * .1),
child: Text(
jokeController.joke.value.value,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: MediaQuery.of(context).size.width * .06,
fontWeight: FontWeight.bold),
),
)),
SizedBox(
height: MediaQuery.of(context).size.height * .2,
),
Container(
alignment: Alignment.bottomCenter,
width: 250,
height: 60,
child: Opacity(
opacity: 0.88,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
shadowColor: Colors.orange),
clipBehavior: Clip.antiAlias,
onPressed: () {
//Refresh the joke
},
child: Ink(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
Colors.orange,
Colors.orange[200]
])),
child: Container(
constraints:
BoxConstraints(maxHeight: 300, minWidth: 50),
alignment: Alignment.center,
child: Text(
"SEE ANOTHER JOKE FROM THIS CATEGORY",
style: TextStyle(
fontSize:
MediaQuery.of(context).size.width * .03,
fontWeight: FontWeight.bold),
),
),
),
)))
],
);
})
What I tried so far under onPressed : jokeController.joke.refresh(); and setState and Get.to(JokePage());
but non of these worked. Also I am getting the category from GetStorage and I take it when user clicked a category from previouspage. That category will not change. Thanks in advance. And a picture from page:
CodePudding user response:
You need to just again call fetchJoke()
method on button pressed event.
You can do like this:
onPressed: () {
jokeController.fetchJoke();//Refresh the joke
},