Search code examples
flutterfirebase-realtime-databasecolorssharedpreferences

Save multiple color data


I started to create/develop a project but at some point I stuck and I couldnt figure it out. Hope you to help!

For now I am changing the color of the container as follows;

InkWell(
        onTap: (){
           setState(() {
               if(_color == null)
               {
                _color = Colors.blue;
               }
               else if(_color == Colors.blue)
               {
                _color = null;
               }
               });
               },
        onDoubleTap: (){
           setState(() {
           if(_color == null)
           {
           _color = Colors.red;
           }
           else if(_color == Colors.red)
           {
           _color = null;
           }
           });
           },
            child: Container(
               height: _height*0.04,
               child: Container(decoration: BoxDecoration(color: _color),)),),

I want to save this color as user information in firestore or keep the data in SharedPreferences.

Also, the number of containers I work with is too many. I don't know how to select / get them one by one. I need your help as soon as possible. Thanks


Solution

  • You can store the value of the Color after tapping.

    onTap: () async {
      setState(() {
        if (_color == null) {
          _color = Colors.blue;
        } else if (_color == Colors.blue) {
          _color = null;
        }
      });
    
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setInt('colorKey', _color.value);
    },
    

    And next time if you start your app you need to read the color from SharedPreferences

    SharedPreferences prefs = await SharedPreferences.getInstance();
    final int colorValue = prefs.getInt('colorKey');
    if (colorValue != null) {
      _color = Color(colorValue);
    }