Flutter本地文件偏好设置插件local_file_preferences的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter本地文件偏好设置插件local_file_preferences的使用

标题

Flutter Local File Preferences

Getting Started 🎉

1pub.dev/packages/local_file_preferences https://mj-studio-library.github.io/flutter-local-file-preferences/


示例代码

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

void main() async {
  var sp = await SharedPreferences.getInstance();
  registerGlobalStorage(SharedPreferencesStorage(sharedPreferences: sp));
  runApp(const MyApp());
}

class LocalFileCounter with LocalFilePrefMixin<int> {
  [@override](/user/override)
  int get fallback =&gt; 0;

  [@override](/user/override)
  String get fileName =&gt; 'counter.dat';

  [@override](/user/override)
  int fromJson(Map<String, dynamic> json) {
    return json['value'] as int;
  }

  [@override](/user/override)
  Map<String, dynamic> toJson() {
    return {'value': value};
  }

  [@override](/user/override)
  Duration get throttleDuration =&gt; const Duration(milliseconds: 1);
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  [@override](/user/override)
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {
  final _counter = LocalFileCounter();

  void _incrementCounter() {
    _counter.value += 1;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: &lt;Widget&gt;[
            const Text(
              'You have pushed the button this many times:',
            ),
            ValueListenableBuilder(
                valueListenable: _counter,
                builder: (context, value, ) {
                  return Text(
                    '$value',
                    style: Theme.of(context).textTheme.headlineMedium,
                  );
                }),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter本地文件偏好设置插件local_file_preferences的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地文件偏好设置插件local_file_preferences的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用local_file_preferences插件来进行本地文件偏好设置的代码案例。请注意,local_file_preferences并非一个官方或广泛使用的插件名称,但基于你的要求,我将假设这个插件允许你以文件形式存储应用偏好设置。

首先,确保你已经在pubspec.yaml文件中添加了该插件的依赖(假设插件名称确实为local_file_preferences,如果实际名称不同,请替换为正确的名称):

dependencies:
  flutter:
    sdk: flutter
  local_file_preferences: ^x.y.z  # 替换为实际的版本号

然后,运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter应用中导入并使用该插件。以下是一个简单的示例,展示如何存储和读取偏好设置:

import 'package:flutter/material.dart';
import 'package:local_file_preferences/local_file_preferences.dart'; // 假设这是插件的导入路径

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Local File Preferences Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  LocalFilePreferences? _preferences;

  @override
  void initState() {
    super.initState();
    // 初始化LocalFilePreferences实例
    _initializePreferences();
  }

  Future<void> _initializePreferences() async {
    _preferences = LocalFilePreferences.getInstance();
    // 读取一个示例设置
    String? themeModeKey = await _preferences!.getString('themeMode');
    if (themeModeKey != null) {
      // 根据读取的设置做一些处理,例如设置应用主题
      // 这里只是简单打印出来
      print('Read theme mode from preferences: $themeModeKey');
    }
  }

  Future<void> _saveThemeMode(String themeMode) async {
    if (_preferences != null) {
      await _preferences!.setString('themeMode', themeMode);
      print('Saved theme mode to preferences: $themeMode');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Local File Preferences Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                await _saveThemeMode('light');
                // 刷新UI或执行其他操作
              },
              child: Text('Set Theme to Light'),
            ),
            ElevatedButton(
              onPressed: () async {
                await _saveThemeMode('dark');
                // 刷新UI或执行其他操作
              },
              child: Text('Set Theme to Dark'),
            ),
          ],
        ),
      ),
    );
  }
}

请注意,上述代码假设LocalFilePreferences类提供了getInstance静态方法用于获取单例实例,以及getStringsetString方法用于读取和存储字符串类型的偏好设置。实际插件的API可能会有所不同,因此请查阅插件的官方文档以获取准确的API信息。

如果local_file_preferences插件实际上并不存在,或者你正在寻找一个具体的、广泛使用的插件(如shared_preferences但用于文件存储),你可能需要寻找或创建一个符合你需求的插件,或者考虑使用其他持久化存储方案,如SQLite数据库或简单的文件I/O操作。

回到顶部