Sharedpreferencs with flutter to save color

柔情痞子 提交于 2020-04-30 06:15:31

问题


I want a container to be of a color, that comes from sharedpreference or something like that! Is there a widget to solve this!! Or can I just do this with sharedpreference!! If I can! How?


回答1:


With flutter SharedPreferences plugin you can only save String, int, StringList, double, Bool.

A work around would be to save the RGBO value of the color in SharedPreferences, this would work for Android and iOS.

Step 1. Install the plugin

pubspec.yaml

Add SharedPreferences to your pubspec.yaml file. Check the last version by clicking here.

dependencies:
  flutter:
    sdk: flutter

  shared_preferences: ^0.5.3+4

Step 2. Save the RGBO value in 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);
  }

Step 3. Retrieve the value and create your color

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);
  }



回答2:


A better way is to save the color.value.

Use

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

to get the color, and

prefs.setInt('color', myColor.value);

to save a color.



来源:https://stackoverflow.com/questions/58261036/sharedpreferencs-with-flutter-to-save-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!