Flutter bool name = String 可能吗?

Flutter bool name = String its possible?

嘿,我做了一个最喜欢的系统,用一个布尔值来表示是否最喜欢。

但是如果 bool 的名称始终相同,它适用于我的所有条目!

但每个条目都有自己的名称 (widget.name),我想也许类似的东西可以工作

bool widget.name;

但这行不通:(

如何解决每个条目都有自己的布尔值?

顺便说一句,我为此使用了这个插件 https://pub.dev/packages/shared_preferences/example

SharedPreferences sharedPreferences;
bool isfavorit;

@override
  void initState() {
    super.initState();

    SharedPreferences.getInstance().then((SharedPreferences sp) {
      sharedPreferences = sp;
      isfavorit = sharedPreferences.getBool(spKey);
      // will be null if never previously saved
      if (isfavorit == null) {
        isfavorit = false;
        persist(isfavorit); // set an initial value
      }
      setState(() {});
    });
  }

    void persist(bool value) {
    setState(() {
      isfavorit = value;
    });
    sharedPreferences?.setBool(spKey, value);
  }

完整代码

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Details extends StatefulWidget {
  final String name;

  Details(
    this.name,
  );

  @override
  _DetailsState createState() => _DetailsState();
}

const String spKey = 'myBool';

class _DetailsState extends State<Details> {
  SharedPreferences sharedPreferences;
  bool isfavorit;

  @override
  void initState() {
    super.initState();

    SharedPreferences.getInstance().then((SharedPreferences sp) {
      sharedPreferences = sp;
      isfavorit = sharedPreferences.getBool(spKey);
      // will be null if never previously saved
      if (isfavorit == null) {
        isfavorit = false;
        persist(isfavorit); // set an initial value
      }
      setState(() {});
    });
  }

  void persist(bool value) {
    setState(() {
      isfavorit = value;
    });
    sharedPreferences?.setBool(spKey, value);
  }

// ignore: missing_return
  IconData favicon() {
    if (isfavorit == true) {
      return Icons.favorite;
    } else if (isfavorit == false) {
      return Icons.favorite_border;
    }
  }

// ignore: missing_return
  Color favicolor() {
    if (isfavorit == true) {
      return Colors.red;
    } else if (isfavorit == false) {
      return Colors.white;
    }
  }

  void changefav() {
    if (isfavorit == true) {
      return persist(false);
    } else if (isfavorit == false) {
      return persist(true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            icon: Icon(
              favicon(),
              color: favicolor(),
            ),
            onPressed: () => changefav(),
          ),
        ],
        title: Text(widget.name),
      ),
      body: Container(
        child: Text(widget.name),
      ),
    );
  }
}

您总是将 isFavorite 保存到共享首选项中的同一个键,而不是使用基于 widget.name

的常量键

例如:

sharedPreferences.getBool('details_favorite_${widget.name}');