Flutter get Data Value from GetStorage List

Issue

i wanna get a Data from GetStorage(),

i got a Shop List and i can use it as Static for only page, that way im saving my List in GetStorage,if i go to another Page that will showed also. Like a SharedPreferences. How can i show a data from GetStorage List Value , like

Text(basket[name]), that will show only the Names,
Text(basket[price]), that will show only Prices,

var basketsd = GetStorage("totalList");

My ProductModel for Shop,

class PriceModel2 {
  final String name;
  final double price;
  PriceModel2({
    this.name,
    this.price,
  });
}

its also not worked.

Text(controller.basketsd.read(["name"])

 Container(
            height: Get.size.height * 0.3,
            child: Obx(() => ListView.builder(
                itemCount: controller.basket.length,
                itemBuilder: (BuildContext context, int index) {
                  return Column(
                    children: [
                      SizedBox(
                        height: 20,
                      ),
                      Container(
                        width: Get.size.width,
                        child: ElevatedButton(
                            onPressed: () {
                              controller.basket
                                  .remove(controller.basket[index]);
                            },
                            child: (Text(controller.basketsd.read(["name"]) +
                                " " +
                                controller.basket[index].price.toString() +
                                " €"))),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                    ],
                  );
                })),
          ),

Codes show like this ,
(https://prnt.sc/1fs6mbf)

Solution

There’s a couple issues here. At least from what you’re sharing, you’re never really storing your PriceModel2 object properly. If you try and store a random custom object, GetStorage will not know what to do with it. (Neither would SharedPreferences in the same scenario).

So for starters, you can implement a toMap function that converts it to a map that GetStorage can read.

Add this to your PriceModel2 class.

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'price': price,
    };
  }

Then you add a named constructor in the same class so you can create your object from the Map that you stored.

 PriceModel2.fromMap(Map map)
      : name = map['name'],
        price = map['price'];

I also suggest, regardless of whichever storage library you’re using, keeping all storage related functionality, including boxes in this case, in its own class, that stores and returns whatever data you need. This way if you ever need to upgrade to Hive, ObjectBox etc… you do it in one class and not all over your app.

An example would look like this.

class Database extends GetxController {
  final box = GetStorage();

  Future<void> initStorage() async {
    await GetStorage.init();
  }

  void storePriceModel(PriceModel2 model) {
    box.write('model', model.toMap());
  }

  PriceModel2 restoreModel() {
    final map = box.read('model') ?? {};
    return PriceModel2.fromMap(map);
  }
}

Then you would initialize your controller and storage in main.

void main() async {
  await Get.put(Database()).initStorage();
  runApp(MyApp());
}

An example of storing a model would look like this.

     ElevatedButton(
              onPressed: () {
                final model = PriceModel2(name: 'test name', price: 23.0);
                Get.find<Database>().storePriceModel(model);
              },
              child: Text('Store Model'),
            ),

And displaying the storage data in the UI could be done like so.

Text(Get.find<Database>().restoreModel().name)

You don’t need an Obx just to display the stored data because its not an observable stream based variable.

As for displaying a list of products you do the same thing but store a list of maps instead of a single map.

If you need help with that then share how you’re trying to add and store to the PriceModel2 list.

Answered By – Loren.A

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.