Flutter 共享偏好颜色主题

问题描述 投票:0回答:1

这是创建 2 个可点击容器的代码。

每个容器都会改变背景颜色。

我想在重新启动应用程序时保存背景颜色。

我知道我需要使用shared_preference,但我不知道在哪里放置“themeColor”变量。

如果有人可以帮助我,那就太好了。

谢谢你

class _ColorSaveState extends State<ColorSave> {

  //VARIABLE
  var themeColor = Colors.red[100];

  //METHOD CHANGE COLOR
  colorBackground(String color){
    setState(() {
      if(color == "themeBlue"){
        themeColor = Colors.blue;
      }else{
        themeColor = Colors.green;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('ColorSave'),
        backgroundColor: Colors.blue,
      ),

      //I would like to save the state of 'themeColor'
      backgroundColor: themeColor,
      body: Center(
        child: Column(
          children:<Widget>[

            //Two Container Clickable
            InkWell(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
            ),
              onTap: (){
                colorBackground("themeBlue");
              },
            ),
            InkWell(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.green,
              ),
              onTap: (){
                colorBackground("themeGreen");
              },
            ),
          ]
        )
      )
    );
  }
}
flutter sharedpreferences
1个回答
0
投票

这是正确的代码:

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

class ColorSave extends StatefulWidget {
  @override
  _ColorSaveState createState() => _ColorSaveState();
}

class _ColorSaveState extends State<ColorSave> {
  // Default background color
  Color? themeColor = Colors.red[100];

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

  // Method to load color from SharedPreferences
  Future<void> loadColor() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String? colorName = prefs.getString('themeColor');
    setState(() {
      if (colorName == 'themeBlue') {
        themeColor = Colors.blue;
      } else if (colorName == 'themeGreen') {
        themeColor = Colors.green;
      } else {
        themeColor = Colors.red[100]; 
      }
    });
  }

  // Method to save color to SharedPreferences
  Future<void> saveColor(String colorName) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('themeColor', colorName);
  }

  // Method to change color
  void colorBackground(String color) {
    setState(() {
      if (color == "themeBlue") {
        themeColor = Colors.blue;
      } else {
        themeColor = Colors.green;
      }
    });
    saveColor(color);  // Save the selected color
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('ColorSave'),
        backgroundColor: Colors.blue,
      ),
      backgroundColor: themeColor,
      body: Center(
        child: Column(
          children: <Widget>[
            InkWell(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
              ),
              onTap: () {
                colorBackground("themeBlue");
              },
            ),
            InkWell(
              child: Container(
                width: 100,
                height: 100,
                color: Colors.green,
              ),
              onTap: () {
                colorBackground("themeGreen");
              },
            ),
          ]
        )
      )
    );
  }
}

此代码在加载小部件时从

SharedPreferences
初始化颜色,并在用户点击容器时更新存储的颜色。颜色名称以字符串形式存储在
SharedPreferences
中,再次启动应用程序时,保存的颜色将应用于背景。

© www.soinside.com 2019 - 2024. All rights reserved.