我正在用getx创建一个应用程序。我有简单的GET请求,我把数据显示在屏幕上。在详细信息屏幕上,我放了一个按钮来刷新请求,请求的响应是随机的,所以每次用户按下按钮时都会显示不同的文本。我不知道如何做到这一点。
我的控制者:
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);
}
}
}
我的请求:
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;
}
}
页面中(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),
),
),
),
)))
],
);
})
到目前为止,我在onPressed
下尝试了以下操作:
jokeController.joke.refresh();
setState ((){});
Get.to(JokePage());
但这些都不起作用。我也从GetStorage获取类别,当用户单击上一页的类别时,我会将其获取。该类别不会更改。提前感谢。我还包括该页的图片:
2条答案
按热度按时间6yoyoihd1#
你需要再次调用
fetchJoke()
方法来处理按钮按下事件。你可以这样做:tyg4sfes2#
https://pub.dev/packages/get
和/或