Flutter设置管理插件clean_settings_nnbd的使用

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

Flutter设置管理插件clean_settings_nnbd的使用

clean_settings_nnbd

clean_settings_nnbd 是一个用于管理应用设置的Flutter插件。它支持null安全,并且是clean_settings包的一个分支。如果您有任何与null安全无关的建议或问题,请将其提交到原始仓库。

完整示例Demo

以下是一个完整的示例,展示了如何在Flutter应用中使用clean_settings_nnbd插件来管理各种设置项。

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

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

class MyApp extends StatelessWidget {
  // 这个小部件是您的应用的根。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  [@override](/user/override)
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int counter = 0;
  String theme = 'System Default';
  bool smartReply = false;
  String? autoReplyMessage;
  int daysOfMailToSync = 5;

  int chosenReplyOptionIndex = 1;
  DateTime dateOfBirth = DateTime.now();
  DateTime scheduledEmailDateTime = DateTime.now();
  TimeOfDay dailyEmailAt = TimeOfDay(hour: 9, minute: 0);

  bool disableDemoItems = false;

  bool smartCompose = true;

  [@override](/user/override)
  Widget build(BuildContext context) {
    String dateOfBirthSlug =
        "${dateOfBirth.year.toString()}-${dateOfBirth.month.toString().padLeft(2, '0')}-${dateOfBirth.day.toString().padLeft(2, '0')}";
    String scheduledEmailSlug =
        "${scheduledEmailDateTime.year.toString()}-${scheduledEmailDateTime.month.toString().padLeft(2, '0')}-${scheduledEmailDateTime.day.toString().padLeft(2, '0')} ${scheduledEmailDateTime.hour.toString().padLeft(2, '0')}:${scheduledEmailDateTime.minute.toString().padLeft(2, '0')}";

    var replyOptions = ['Reply', 'Reply All', 'Last Chosen', 'None'];
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'App Settings',
          style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.w300,
              color: Colors.black87),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: Container(
        child: SettingContainer(
          sections: [
            SettingSection(
              title: 'Demo Options',
              items: [
                SettingCheckboxItem(
                  title: 'Disable all items',
                  description: '禁用所有演示选项',
                  priority: ItemPriority.high,
                  value: disableDemoItems,
                  onChanged: (v) => setState(() => disableDemoItems = v != null ? v : false),
                ),
              ],
            ),
            SettingSection(
              title: 'Appearance',
              items: [
                SettingItem(
                  title: '简单计数器',
                  displayValue: counter.toString(),
                  onTap: () => setState(() => counter++),
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingItem(
                  title: '启动独角兽创业',
                  displayValue: '筹集数十亿美元',
                  onTap: () => setState(() => counter++),
                  priority: ItemPriority.disabled,
                ),
                SettingRadioItem<String>(
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                  title: '主题',
                  displayValue: '$theme 主题',
                  selectedValue: theme,
                  items: [
                    SettingRadioValue('Light', 'Light'),
                    SettingRadioValue('Dark', 'Dark'),
                    SettingRadioValue('System Default', 'System Default'),
                  ],
                  onChanged: (v) => setState(() => theme = v),
                ),
              ],
            ),
            SettingSection(
              title: '互动',
              items: [
                SettingConfirmItem(
                  title: '删除账户',
                  displayValue: '永久删除您的账户',
                  alertTitle: '删除您的账户',
                  alertMessage: '您确定吗?',
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.high,
                  onConfirm: () => ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                          content: Text('确认!'),
                          duration: Duration(seconds: 3))),
                  onCancel: () => ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                          content: Text('取消!'),
                          duration: Duration(seconds: 3))),
                ),
                SettingRadioItem<String>(
                  title: '主题',
                  displayValue: '$theme 主题',
                  selectedValue: theme,
                  items: [
                    SettingRadioValue('Light', 'Light'),
                    SettingRadioValue('Dark', 'Dark'),
                    SettingRadioValue('System Default', 'System Default'),
                  ],
                  onChanged: (v) => setState(() => theme = v),
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
              ],
            ),
            SettingSection(
              title: '收件箱',
              items: [
                SettingCheckboxItem(
                  title: '智能回复',
                  value: smartReply,
                  onChanged: (v) =>
                      setState(() => smartReply = v != null ? v : false),
                  description: '在可用时显示建议的回复',
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingSwitchItem(
                  title: '智能撰写',
                  value: smartCompose,
                  onChanged: (v) => setState(() => smartCompose = v),
                  description: '显示预测性写作建议',
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingTextItem(
                  title: '自动回复消息',
                  displayValue: autoReplyMessage,
                  initialValue: autoReplyMessage,
                  hintText: '系统发送时',
                  onChanged: (v) => setState(() => autoReplyMessage = v),
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingWheelPickerItem(
                  title: '要同步的邮件天数',
                  displayValue: daysOfMailToSync.toString(),
                  initialValueIndex: daysOfMailToSync,
                  items: List.generate(10, (index) => index.toString()),
                  onChanged: (v) => setState(() => daysOfMailToSync = v),
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingWheelPickerItem(
                  title: '默认回复操作',
                  displayValue: replyOptions[chosenReplyOptionIndex],
                  initialValueIndex: chosenReplyOptionIndex,
                  items: replyOptions,
                  onChanged: (v) => setState(() => chosenReplyOptionIndex = v),
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingDateTimeItem<DateTime>(
                  title: '下次预定电子邮件时间',
                  displayValue: scheduledEmailSlug,
                  onChanged: (v) => setState(() => scheduledEmailDateTime = v),
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingDateTimeItem<DateTime>(
                  title: '出生日期',
                  displayValue: dateOfBirthSlug,
                  onChanged: (v) => setState(() => dateOfBirth = v),
                  timePicker: false,
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
                SettingDateTimeItem<TimeOfDay>(
                  title: '每日唤醒邮件',
                  displayValue: dailyEmailAt.format(context),
                  onChanged: (v) => setState(() => dailyEmailAt = v),
                  datePicker: false,
                  priority: disableDemoItems
                      ? ItemPriority.disabled
                      : ItemPriority.normal,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter设置管理插件clean_settings_nnbd的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter设置管理插件clean_settings_nnbd的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用clean_settings_nnbd插件来管理设置的示例代码。clean_settings_nnbd是一个用于Flutter的设置管理插件,支持非空安全(Null Safety)。

1. 添加依赖

首先,在pubspec.yaml文件中添加clean_settings_nnbd的依赖:

dependencies:
  flutter:
    sdk: flutter
  clean_settings_nnbd: ^最新版本号

请确保将^最新版本号替换为实际的最新版本号。

2. 导入包

在你的Dart文件中导入clean_settings_nnbd包:

import 'package:clean_settings_nnbd/clean_settings_nnbd.dart';

3. 配置Settings

定义一个设置模型类,继承自SettingsModel

import 'package:clean_settings_nnbd/clean_settings_nnbd.dart';

class MySettings extends SettingsModel {
  final String someSetting = 'default_value';
  final bool anotherSetting = false;

  MySettings() : super();

  @override
  Map<String, dynamic> toMap() {
    return {
      'someSetting': someSetting,
      'anotherSetting': anotherSetting,
    };
  }

  @override
  void fromMap(Map<String, dynamic> map) {
    someSetting = map['someSetting'] as String ?? 'default_value';
    anotherSetting = map['anotherSetting'] as bool ?? false;
  }
}

4. 初始化Settings

在你的应用初始化代码中,创建并初始化MySettings实例:

import 'package:flutter/material.dart';
import 'package:clean_settings_nnbd/clean_settings_nnbd.dart';
import 'path/to/your_settings_model.dart'; // 替换为实际的路径

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final MySettings settings = MySettings();

    // 从本地存储加载设置
    settings.load().then((_) {
      // 可以在这里处理加载后的逻辑
    });

    // 监听设置变化
    settings.addListener(() {
      // 每次设置变化时执行的逻辑
    });

    return MaterialApp(
      home: SettingsPage(settings: settings),
    );
  }
}

5. 使用Settings

在你的UI组件中使用设置:

import 'package:flutter/material.dart';
import 'path/to/your_settings_model.dart'; // 替换为实际的路径

class SettingsPage extends StatefulWidget {
  final MySettings settings;

  SettingsPage({required this.settings});

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

class _SettingsPageState extends State<SettingsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Text('Some Setting: ${widget.settings.someSetting}'),
            Switch(
              value: widget.settings.anotherSetting,
              onChanged: (value) {
                setState(() {
                  widget.settings.anotherSetting = value;
                  widget.settings.save();
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

6. 完整示例

将上述代码片段组合成一个完整的示例:

// pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  clean_settings_nnbd: ^最新版本号

// main.dart
import 'package:flutter/material.dart';
import 'package:clean_settings_nnbd/clean_settings_nnbd.dart';

class MySettings extends SettingsModel {
  final String someSetting = 'default_value';
  final bool anotherSetting = false;

  MySettings() : super();

  @override
  Map<String, dynamic> toMap() {
    return {
      'someSetting': someSetting,
      'anotherSetting': anotherSetting,
    };
  }

  @override
  void fromMap(Map<String, dynamic> map) {
    someSetting = map['someSetting'] as String ?? 'default_value';
    anotherSetting = map['anotherSetting'] as bool ?? false;
  }
}

void main() {
  final MySettings settings = MySettings();

  settings.load().then((_) {
    // 处理加载后的逻辑
  });

  settings.addListener(() {
    // 处理设置变化的逻辑
  });

  runApp(MyApp(settings: settings));
}

class MyApp extends StatelessWidget {
  final MySettings settings;

  MyApp({required this.settings});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SettingsPage(settings: settings),
    );
  }
}

class SettingsPage extends StatefulWidget {
  final MySettings settings;

  SettingsPage({required this.settings});

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

class _SettingsPageState extends State<SettingsPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Text('Some Setting: ${widget.settings.someSetting}'),
            Switch(
              value: widget.settings.anotherSetting,
              onChanged: (value) {
                setState(() {
                  widget.settings.anotherSetting = value;
                  widget.settings.save();
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

这样,你就可以在Flutter应用中使用clean_settings_nnbd插件来管理你的设置了。

回到顶部