Search code examples
flutterdartflutter-getx

Flutter, GetX initState


can someone explain how to use onInit in GetX and is it important to use the dispose/onClose ?

i want to GET api data and show it from the start of the app

already googled it didn't find anything helpful :(


Solution

  • class ShoppingController extends GetxController {
      List<ProductModel> products = <ProductModel>[].obs;
    
      @override
      void onInit() {
        // TODO: implement onInit
        super.onInit();
        getData();
      }
    
      Future<List<ProductModel>> getData() async {
        QuerySnapshot querySnapshot =
            await FirebaseFirestore.instance.collection('Products').get();
        products = querySnapshot.docs
            .map((m) => ProductModel.fromJson(m.data() as Map<String, dynamic>))
            .toList();
        return products;
      }
    }