简体   繁体   English

Flutter 使用共享首选项按 id 保存数据

[英]Flutter save data by id using Shared Preferences

I have a listView, in which I have some products.我有一个 listView,其中有一些产品。 I wanted a rating system on each product details page so I go through this answer How to save User rating in flutter rating bar?.我想要在每个产品详细信息页面上都有一个评级系统,所以我通过了这个答案 How to save User rating in flutter rating bar?。 Now the problem is that I am getting my star rating the same on each product detail page.现在的问题是我在每个产品详细信息页面上的星级评分都相同。 Now please suggest to me, to save the value of the star with respect to product id in my shared preferences.现在请向我建议,在我的共享首选项中保存与产品 ID 相关的星级值。

Or anyone has another solution please share it with me.或者任何人有其他解决方案,请与我分享。

Rating Controller评级控制器

class RatingController extends GetxController {
  int currentRating = 0;
  final box = GetStorage();

  late SharedPreferences prefs;

  @override
  void onInit() { // called whenever we initialize the controller
    super.onInit();
    currentRating = box.read('rating') ?? 0; // initializing current rating from storage or 0 if storage is null
  }

  void updateAndStoreRating(int rating) {
    currentRating = rating;
    prefs.setInt('rating', rating); //SharedPreferences way
    update(); // triggers a rebuild of the GetBuilder Widget
  }
  Future<void> initSp() async {
    prefs = await SharedPreferences.getInstance();
    currentRating = prefs.getInt('rating') ?? 0;
  }

  Widget buildRatingStar(int index) {
    if (index < currentRating) {
      return Icon(
        Icons.star,
        color: Colors.yellow,
      );
    } else {
      return Icon(
        Icons.star,
        color: Colors.white,
      );
    }
  }
}

Rating Widget评级小工具

SharedPreferences? _prefs;
 

  final controller = Get.find<RatingController>();

  Widget _buildBody() {
    final stars = List<Widget>.generate(5, (index) {
      return GetBuilder<RatingController>( // rebuilds when update() is called from GetX class
        builder: (controller) => Expanded(
          child: GestureDetector(
            child: controller.buildRatingStar(index),
            onTap: () {
              controller.updateAndStoreRating(index + 1);
              print(index + 1);// +1 because index starts at 0 otherwise the star rating is offset by one
            },
          ),
        ),
      );
    });
    return Row(
      children: [
        Expanded(
          child: Row(
            children: stars,
          ),
        ),
        Expanded(
          child: TextButton(
            onPressed: () {
              controller.updateAndStoreRating(0);
            },
            child: Text(
              "Clear",
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
      ],
    );
  }

This working and saving star values but I am getting this value in all my list data's detail page.这个工作和保存星级值,但我在所有列表数据的详细信息页面中都得到了这个值。 so please suggest me to save using particular index.所以请建议我使用特定索引保存。

GetStorage cant save Map based data type and in your case it's better to use Hive : GetStorage无法保存基于Map的数据类型,在您的情况下,最好使用Hive

First, add hive to your dependencies:首先,将 hive 添加到您的依赖项中:

  hive: ^2.0.4
  hive_flutter: ^1.1.0

Then initialize it at the beginning of the application:然后在应用程序开始时对其进行初始化:

await Hive.initFlutter();

And use it like this:并像这样使用它:

var box = await Hive.openBox('myBox');
var person = Person()
  ..name = 'Dave'
  ..age = 22;
box.add(person);
print(box.getAt(0)); // Dave - 22
person.age = 30;
person.save();
print(box.getAt(0)) // Dave - 30

You can see more examples about using hive in this link .您可以在此链接中查看有关使用 hive 的更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM