Search code examples
flutterflutter-getx

Flutter - GetX: The list literal type 'List<Item>' isn't of expected type 'RxList<Item>'


I'm a beginner of Flutter. I'm making a sort of shopping list app. Using this tutorial https://www.youtube.com/watch?v=ZnevdXDH25Q I'm trying to use GetX for state management.

I have this class named 'Items' which has some attributes. I create a list of Items which I'll later show as cards.

I can't wrap my head around this.

This is the code of the class on which I'm working right now.

class ItemsController extends GetxController {
  RxList<Item> items = [].obs;

  @override
  void onInit() {
    super.onInit();
    loadItems();
  }

  loadItems() {
    items = [
      Item(
        name: 'olio',
        description: '',
        quantity: 1,
      ),
      Item(
        name: 'mozzarella',
        description: 'di bufala',
        quantity: 4,
      ),
    ];

    items.assignAll(items);
  }
}

I tried almost everything I could, but everytime Android Studio gives this error: The list literal type 'List' isn't of expected type 'RxList'.

I also tried to append .cast<Item>(); to 'items' list but I have the message

type 'RxList<dynamic>' is not a subtype of type 'RxList<Item>'

Solution

    • You have assigned a List to RxList so change that to
      RxList<Item> items = <Item>[].obs;
    

    or just

      var items = [].obs;
    
    • In the loadItems function you have assigned a List to RxList so change that as follows
      loadItems() {
        List<Item> newItems = [
          Item(
            name: 'olio',
            description: '',
            quantity: 1,
          ),
          Item(
            name: 'mozzarella',
            description: 'di bufala',
            quantity: 4,
          ),
        ];
        items.assignAll(newItems);
      }
    

    or simply

      loadItems() {
        items.assignAll([
          Item(
            name: 'olio',
            description: '',
            quantity: 1,
          ),
          Item(
            name: 'mozzarella',
            description: 'di bufala',
            quantity: 4,
          ),
        ]);
      }
    

    it's a bit confusing at the start but you will get the get little by little