与颤振共享偏好以节省颜色

Sad*_*had 2 flutter flutter-layout

我想要一个容器的颜色,它来自 sharedpreference 或类似的东西!有没有小工具可以解决这个问题!!或者我可以用sharedpreference来做到这一点!!如果我能!如何?

Dah*_*son 5

更好的方法是保存color.value.

final prefs = await SharedPreferences.getInstance();
Color myColor = Color(prefs.getInt('color') ?? Colors.blue.value);
// change Colors.blue to a default color
Run Code Online (Sandbox Code Playgroud)

获得颜色,和

prefs.setInt('color', myColor.value);
Run Code Online (Sandbox Code Playgroud)

保存颜色。


Soo*_*tos 3

使用 flutter SharedPreferences插件,您只能保存String, int, StringList, double, Bool.

解决方法是将RGBO颜色值保存在 中SharedPreferences,这适用于 Android 和 iOS。

步骤1.安装插件

pubspec.yaml

将 SharedPreferences 添加到您的pubspec.yaml文件中。单击此处查看最新版本。

dependencies:
  flutter:
    sdk: flutter

  shared_preferences: ^0.5.3+4
Run Code Online (Sandbox Code Playgroud)

步骤 2. 将 RGBO 值保存在 SharedPreferences 中

  void saveColor(int r, int g, int b, double opacity) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setInt('r', r);
    prefs.setInt('g', g);
    prefs.setInt('b', b);
    prefs.setDouble('o', opacity);
  }
Run Code Online (Sandbox Code Playgroud)

步骤 3. 检索值并创建您的颜色

getColor() async {
    final prefs = await SharedPreferences.getInstance();
    final r = prefs.getInt('r');
    final g = prefs.getInt('g');
    final b = prefs.getInt('b');
    final opacity = prefs.getDouble('o');
    return Color.fromRGBO(r, g, b, opacity);
  }
Run Code Online (Sandbox Code Playgroud)