Issue
Hello everyone i need help with getx state management,
I have a boolean value loading by default it’s false after that it changes after loading data
RxBool loading=false.obs;
List<String> texts =<String>[].obs;
getData()async {
print('loadimg :' + loading.value.toString());
loading=true.obs; print('loadimg :' + loading.value.toString());
var result = await http.get(Uri.parse(main_url));
print(result.statusCode.toString());
var data = json.decode(result.body);
data.forEach((element) => texts.add(element["title"]));
print(data);
loading=false.obs;
print('loadimg :' + loading.value.toString());
}
And i need to check this value if it’s true i show a widget otherwise i show another widget
but when i call this boolean value into the second screen it always true
class _HomePageState extends State<HomePage> {
PostController controller = Get.put(PostController());
@override
void initState() {
// TODO: implement initState
super.initState();
controller.getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('App'),),
body:controller.loading.isTrue? Center(child: CircularProgressIndicator()): ListView.builder(itemBuilder: (context,index){
return Card(child: ListTile(title: Text(controller.texts[index],style: TextStyle(color: Colors.black,fontSize: 24),)));
},itemCount: controller.texts.length,),
);
Solution
You forgot to wrap scaffold body content with an Obx
widget or similar ones that listens to observable changes and rebuild the ui.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('App'),
),
body: Obx(() => controller.loading.isTrue
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(
controller.texts[index],
style: TextStyle(color: Colors.black, fontSize: 24),
)));
},
itemCount: controller.texts.length,
)),
);
}
Also, on your controller you don’t have to re-assign loading
variable everytime. Just do it like this loading.value = true;
Answered By – HasilT
Answer Checked By – Jay B. (FlutterFixes Admin)