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

在Flutter中如何将Widget的数据保存到设备本地?

基于shared_preferences实现文件访问列表存储方案

前置准备

首先在项目的pubspec.yaml中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2 # 可替换为最新稳定版

执行flutter pub get完成依赖安装。

核心逻辑实现

shared_preferences支持存储字符串列表类型,你可以将需要便捷访问的文件的本地存储路径、文件名等轻量信息存在字符串列表中,实现持久化。

1. 封装存储读写方法

import 'package:shared_preferences/shared_preferences.dart';

// 存储文件路径列表
Future<void> saveFileList(List<String> filePaths) async {
  final sp = await SharedPreferences.getInstance();
  await sp.setStringList('access_file_list', filePaths);
}

// 读取已存储的文件路径列表
Future<List<String>> getFileList() async {
  final sp = await SharedPreferences.getInstance();
  // 无存储数据时返回空列表,避免空指针异常
  return sp.getStringList('access_file_list') ?? [];
}

2. 结合ListView.builder渲染列表

使用FutureBuilder异步读取存储数据后渲染列表:

class AccessFileList extends StatefulWidget {
  const AccessFileList({super.key});

  @override
  State<AccessFileList> createState() => _AccessFileListState();
}

class _AccessFileListState extends State<AccessFileList> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<String>>(
      future: getFileList(),
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Text('暂无快捷访问文件');
        }
        final fileList = snapshot.data!;
        return ListView.builder(
          itemCount: fileList.length,
          itemBuilder: (context, index) {
            final filePath = fileList[index];
            // 自定义列表项,点击可跳转打开对应文件
            return ListTile(
              title: Text(filePath.split('/').last), // 取文件名展示
              onTap: () => openFile(filePath), // 替换为你自己的打开文件逻辑
            );
          },
        );
      },
    );
  }
}

3. 新增文件时更新存储

每次新增需要快捷访问的文件时,更新存储的列表后刷新UI即可:

Future<void> addNewAccessFile(String newFilePath) async {
  // 先读取现有列表
  final oldList = await getFileList();
  // 去重后加入新文件路径
  if (!oldList.contains(newFilePath)) {
    oldList.add(newFilePath);
    // 保存新列表
    await saveFileList(oldList);
    // 刷新UI
    setState(() {});
  }
}

注意事项

  • shared_preferences仅用于存储轻量数据,不要直接存储文件本身,只存文件的本地绝对路径即可
  • 如果需要存储文件名、创建时间、文件大小等更多元数据,可以将每个文件的信息序列化为JSON字符串后再存入列表
  • 存储的路径要确保是应用可访问的本地路径,避免权限问题导致无法打开文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:06:04