我正在使用 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 獲取類別,當用戶單擊上一頁中的類別時,我會使用它。該類別不會改變。提前致謝。以及來自頁面的圖片:

uj5u.com熱心網友回復:
您需要再次呼叫fetchJoke()按鈕按下事件的方法。你可以這樣做:
onPressed: () {
jokeController.fetchJoke();//Refresh the joke
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/354866.html
上一篇:如何在Flutter中的頁面轉換期間避免卡頓(延遲影片)
下一篇:如何為svg影片留出更多空間?
