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

如何在Flutter的main.dart中持久化布尔状态,实现跨重启全局可用

问题解决:Flutter中已验证状态的持久化与全局共享

问题说明

在Dashboard页面点击ListTile标记卡片为已验证后,布尔状态_verified会从false切换为true,但关闭或重启应用后状态会重置为false。需要实现状态永久保留,且能在多页面共用。

解决方案

使用shared_preferences包实现本地持久化存储,同时封装全局工具类来管理状态,确保多页面可访问。

步骤1:添加依赖

在pubspec.yaml中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2

执行flutter pub get安装依赖。

步骤2:封装全局存储工具类

创建storage_service.dart文件,统一管理本地存储:

import 'package:shared_preferences/shared_preferences.dart';

class StorageService {
  static late SharedPreferences _prefs;

  // 初始化存储
  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  // 设置已验证状态
  static Future<void> setVerified(bool value) async {
    await _prefs.setBool('is_verified', value);
  }

  // 获取已验证状态
  static bool getVerified() {
    return _prefs.getBool('is_verified') ?? false;
  }
}

步骤3:修改main.dart初始化存储

在main函数中初始化存储服务:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'storage_service.dart';
import 'dashboard.dart';
import 'splash_screen.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  // 初始化存储服务
  await StorageService.init();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'My Flutter App',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSwatch(
          primarySwatch: Colors.green,
          backgroundColor: Colors.white,
        ),
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => const SplashScreen(),
        '/dashboard': (context) => const Dashboard(),
      },
    );
  }
}

步骤4:修改Dashboard页面状态管理

更新Dashboard页面,从存储读取初始状态,点击时同步更新存储:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'storage_service.dart';

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

  @override
  _DashboardState createState() => _DashboardState();
}

class _DashboardState extends State<Dashboard> {
  bool _verified = false;
  bool isFetching = false;
  late String cardInfo = retrieveData; // 你的PHP接口地址
  List cardData = [];
  Color col = Colors.grey; // 初始化图标颜色
  final Color iconTip = Colors.green; // 验证后的颜色

  Future<void> getCardData() async {
    setState(() => isFetching = true);
    var response = await http.get(Uri.parse(cardInfo));
    if (response.statusCode == 200) {
      setState(() {
        cardData = json.decode(response.body);
      });
    }
    setState(() => isFetching = false);
  }

  @override
  void initState() {
    super.initState();
    getCardData();
    // 从存储中读取初始状态
    _verified = StorageService.getVerified();
    // 根据状态设置图标颜色
    if (_verified) {
      col = iconTip;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Approve Card'),
        centerTitle: true,
      ),
      body: isFetching
          ? const Center(child: CircularProgressIndicator())
          : Container(
              child: Card(
                child: ListView.builder(
                  physics: const ClampingScrollPhysics(),
                  shrinkWrap: true,
                  primary: false,
                  itemCount: cardData.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      leading: Container(
                        padding: const EdgeInsets.only(left: 15.0),
                        alignment: Alignment.center,
                        height: 50,
                        width: 50,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50.0),
                          image: DecorationImage(
                            image: NetworkImage(
                                'http://url/uploads/${cardData[index]['logo']}'),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      title: Text(
                        cardData[index]['name'],
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      subtitle: Text(cardData[index]['email']),
                      trailing: GestureDetector(
                        onTap: () async {
                          setState(() {
                            col = iconTip;
                            _verified = true;
                          });
                          // 更新存储中的状态
                          await StorageService.setVerified(true);
                          // 提交到后端
                          var url = Uri.parse(verifiedCards); // 你的验证接口地址
                          await http.post(url, body: {
                            "card": cardData[index]['card'],
                          });
                          await getCardData();
                        },
                        child: Container(
                          padding: const EdgeInsets.all(15.0),
                          color: col,
                          child: const Icon(Icons.check_sharp),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
    );
  }
}

关键说明

  • 用SharedPreferences实现本地持久化,确保应用重启后状态不丢失
  • 封装的StorageService类可在任何页面调用,实现状态全局共享
  • 初始化时从存储读取状态,更新时同步写入存储,保证状态一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:48:16