Never give up

Flutter - SharedPreferences set and get Color 본문

Flutter

Flutter - SharedPreferences set and get Color

대기만성 개발자 2020. 8. 3. 16:37
반응형

Color값을 SharedPreferences에 저장하는것은 아주 간단하지만

이전에 설정된 값이 없어서 null인 경우에 처리하는 방법입니다

Splash Screen, init메소드

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

void _init() async {
  await Provider.of<ConfigData>(context, listen: false).initColorData();

  Navigator.push(
      context, MaterialPageRoute(builder: (context) => MainScreen()));
}

 

ConfigData

class ConfigData extends ChangeNotifier {
  SharedPreferences _preferences;
  Color _color;

  Future<void> initColorData() async {
    _preferences = await SharedPreferences.getInstance();
    _color = Color(_preferences.getInt('color') ?? Colors.blue.value);
  }

  Color get getColor => _color;

  void setColor(Color value) async {
    _color = value;
    notifyListeners();
    await _preferences.setInt('color', _color.value);
  }
}

 

메인

class _SharedPreferencesExampleState extends State<SharedPreferencesExample> {
  @override
  Widget build(BuildContext context) {
    var item = Provider.of<ConfigData>(context);
    Color _color;
    return Scaffold(
      appBar: AppBar(title: Text('SharedPreferences')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: MediaQuery.of(context).size.height * 0.25,
              width: MediaQuery.of(context).size.width * 0.5,
              color: item.getColor,
            ),
            SizedBox(height: 10),
            RaisedButton(
                child: Text('Change color'),
                onPressed: () => showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                          title: Text('Pick Color',
                              style: TextStyle(
                                  fontSize: 24, fontWeight: FontWeight.bold)),
                          content: MaterialColorPicker(
                            shrinkWrap: true,
                            selectedColor: item.getColor,
                            onColorChange: (color) {
                              _color = color;
                            },
                          ),
                          actions: <Widget>[
                            FlatButton(
                                child: Text('Cancel'),
                                onPressed: () => Navigator.pop(context)),
                            FlatButton(
                                child: Text('Confirm'),
                                onPressed: () {
                                  if (_color == null) {
                                    _color = item.getColor;
                                  }
                                  item.setColor(_color);
                                  Navigator.pop(context);
                                }),
                          ],
                        )))
          ],
        ),
      ),
    );
  }
}

 

int나 String같은 값을 가져올때에는 preferences.getInt() ?? 0, preferences.getString() ?? '0'

이런식으로 default값을 처리해주면 되지만

다른 데이터 타입을 갖는경우 ex) Color, DateTime, etc

본문과 같이 처리를 해줘야됩니다

반응형
Comments