You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用SharedPreferences修改的变量重启后失效问题求助

问题原因分析

你的代码存在三个核心问题导致重启后字体大小重置:

  1. 未在启动时加载保存的配置:每次App重启,CountPage的_font都会被初始化为默认值40,没有从SharedPreferences读取之前保存的用户设置。
  2. 状态变更未通知UI:CountPage的font setter没有调用notifyListeners(),即使后续读取了保存值,也无法触发UI更新;你在按钮点击时用setState()属于冗余操作,不符合Provider的状态管理逻辑。
  3. 缺少Flutter绑定初始化:使用SharedPreferences前未调用WidgetsFlutterBinding.ensureInitialized(),可能导致异步操作出现异常。

修复方案

以下是针对三个文件的修改代码:

1. 修改count_page.dart

添加配置加载/保存方法,在状态变更时通知UI:

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

class CountPage extends ChangeNotifier {
  double _font = 40;
  final String _prefsKey = "prefs_font";

  double get font => _font;

  set font(double font) {
    _font = font;
    notifyListeners(); // 通知UI状态变更
    _saveFontToPrefs(); // 自动保存到本地
  }

  // 从本地加载保存的字体大小
  Future<void> loadFontFromPrefs() async {
    final prefs = await SharedPreferences.getInstance();
    final savedFont = prefs.getDouble(_prefsKey);
    if (savedFont != null) {
      _font = savedFont;
      notifyListeners();
    }
  }

  // 保存字体大小到本地
  Future<void> _saveFontToPrefs() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_prefsKey, _font);
  }
}

2. 修改main.dart

异步初始化App,先加载配置再创建Provider:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './HomePage.dart';
import 'count_page.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // 初始化Flutter绑定
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initCountPage(), // 异步加载配置并初始化CountPage
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return ChangeNotifierProvider.value(
            value: snapshot.data as CountPage,
            child: MaterialApp(
              debugShowCheckedModeBanner: false,
              theme: ThemeData(
                primarySwatch: Colors.blue,
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
              ),
              home: HomePage(),
            ),
          );
        } else {
          // 加载配置时显示加载动画
          return const MaterialApp(
            home: Scaffold(
              body: Center(child: CircularProgressIndicator()),
            ),
          );
        }
      },
    );
  }

  // 初始化CountPage并加载本地配置
  Future<CountPage> _initCountPage() async {
    final countPage = CountPage();
    await countPage.loadFontFromPrefs();
    return countPage;
  }
}

3. 修改HomePage.dart

简化按钮逻辑,移除冗余的setState()和重复的SharedPreferences操作:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './count_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late CountPage _countPage;

  @override
  Widget build(BuildContext context) {
    _countPage = Provider.of<CountPage>(context, listen: true);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: const Text('Test_Code'),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: Container(
        color: Colors.white,
        child: Center(
          child: Text('Font_size', style: TextStyle(fontSize: _countPage.font)),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color: Colors.lime,
        child: Container(
          height: 200,
          child: Row(
            children: [
              IconButton(
                onPressed: () => _countPage.font = 10,
                icon: const Icon(Icons.looks_one_outlined),
              ),
              IconButton(
                onPressed: () => _countPage.font = 40,
                icon: const Icon(Icons.looks_two_outlined),
              ),
              IconButton(
                onPressed: () => _countPage.font = 80,
                icon: const Icon(Icons.looks_3_outlined),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者GodHanmin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:16