我正在使用 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 獲取類別,當用戶單擊上一頁中的類別時,我會使用它。該類別不會改變。提前致謝。以及來自頁面的圖片:
您需要再次調用fetchJoke()
按鈕按下事件的方法。你可以這樣做:
onPressed: () {
jokeController.fetchJoke();//Refresh the joke
},
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句