Flutter应用设置管理插件cobi_flutter_settings的使用

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

Flutter应用设置管理插件cobi_flutter_settings的使用

cobi_flutter_settings 是一个用于创建应用设置界面的 Flutter 插件。它通过 shared_preferences 包来持久化存储设置值。

开始使用

所有小部件都有一个名为 settingsKey 的属性,用于将它们存储在 shared_preferences 中。这样你就可以从任何地方使用相同的键检索这些值。唯一例外的是 SettingsScreenSettingsGroupCustomSetting(它们用于启动导航路由或仅显示一些信息)。

小部件

SettingsScreen

这是最高级别的设置容器。用它作为起点。

SettingsScreen (
  title: 'App Settings',
  children: [],
)

SettingsGroup

这是一个用于分组各种设置的小部件。

SettingsGroup (
  title: 'First Group',
  children: [],
)

CustomSetting

一个带有 onPressed 动作的设置小部件,例如用于启动导航路由。

CustomSetting (
  title: 'My Custom Setting',
  subtitle: 'My subtitle',
  onPressed: () => debugPrint('hello world!'),
)

TextSetting

一个显示文本框的小部件。

TextSetting<int>(
  settingsKey: 'text-setting',
  title: 'A text setting for integers only',
  keyboardType: TextInputType.number,
  defaultValue: 42000,
  validator: (value) {
    if (value == null || value < 1024 || value > 65536) {
      return 'Integer number between 1024 and 65536 expected';
    }
  },
),

ImageSetting

一个带有图像选择器的小部件,存储文件名作为字符串。

ImageSetting(
  settingsKey: 'image-setting',
  title: 'This is an image setting'
),

SwitchSetting

一个带有双状态开关的小部件。

SwitchSetting(
  settingsKey: 'switch-setting',
  title: 'This is a switch setting',
  defaultValue: true,
)

CheckboxSetting

一个带有复选框的小部件。

CheckboxSetting(
  settingsKey: 'checkbox-setting',
  title: 'This is a checkbox setting',
  defaultValue: false,
),

RadioSetting

这个小部件显示一组单选按钮。

RadioSetting<int>(
  settingsKey: 'radio-setting',
  title: 'This is a radio setting',
  items: [
    ListItem<int>(value: 1, caption: 'One'),
    ListItem<int>(value: 2, caption: 'Two'),
    ListItem<int>(value: 3, caption: 'Three'),
    ListItem<int>(value: 4, caption: 'Four'),
    ListItem<int>(value: 5, caption: 'Five'),
  ],
),

RadioModalSetting

这个小部件中的单选按钮显示在一个对话框中。

RadioModalSetting<int>(
  settingsKey: 'radio-modal-setting',
  title: 'This is a modal radio setting',
  defaultValue: 5,
  items: [
    ListItem<int>(value: 1, caption: 'One'),
    ListItem<int>(value: 2, caption: 'Two'),
    ListItem<int>(value: 3, caption: 'Three'),
    ListItem<int>(value: 4, caption: 'Four'),
    ListItem<int>(value: 5, caption: 'Five'),
    ListItem<int>(value: 6, caption: 'Six'),
  ],
),

SliderSetting

顾名思义,一个带有滑块的小部件。

SliderSetting(
  settingsKey: 'slider-setting',
  title: 'This is a slider setting',
  minValue: 0.0,
  maxValue: 100.0,
  divisions: 100,
  defaultValue: 25.0,
),

MultiSelectSetting

一个显示多选列表的小部件。

MultiSelectSetting<String>(
  settingsKey: 'multi-select-setting',
  title: "A multi-select setting",
  items: [
    ListItem(value: "hello", caption: "Hello"),
    ListItem(value: "world", caption: "World"),
    ListItem(value: "foo", caption: "foo"),
    ListItem(value: "bar", caption: "bar"),
  ]
),

完整示例

你可以找到更多示例用法在包含的示例应用程序中。

以下是一个完整的示例代码:

import 'package:cobi_flutter_settings/cobi_flutter_settings.dart';
import 'package:cobi_flutter_settings_example/types.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSwatch(
          primarySwatch: Colors.indigo,
          accentColor: Colors.indigoAccent
        )
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings Example'),
      ),
      body: SettingsScreen(
        title: 'App Settings',
        children: [
          SettingsGroup(
            title: 'Switchable Settings with different header color',
            style: TextStyle(
              color: Colors.teal,
            ),
            children: [
              SwitchSetting(
                settingsKey: 'switch-setting',
                title: 'This is a switch setting',
                defaultValue: true
              ),
              CheckboxSetting(
                settingsKey: 'checkbox-setting',
                title: 'This is a checkbox setting',
                defaultValue: false,
              ),
            ],
          ),
          ImageSetting(
            settingsKey: 'image-setting',
            title: 'This is an image setting',
            showPreview: true,
          ),
          SettingsGroup(
            title: 'Text Settings',
            children: [
              TextSetting<String>(
                settingsKey: 'text-setting',
                title: 'A text setting with default keyboard type',
              ),
              TextSetting<String>(
                settingsKey: 'text-setting-2',
                title: 'This a text setting with a specified subtitle',
                subtitle: 'This is a subtitle'
              ),
              TextSetting<int>(
                settingsKey: 'text-setting-3',
                title: 'A text setting for integers only',
                keyboardType: TextInputType.number,
                defaultValue: 42000,
                validator: (value) {
                  if (value == null || value < 1024 || value > 65536) {
                    return 'Integer number between 1024 and 65536 expected';
                  }
                  return "";
                },
              ),
              TextSetting<double>(
                settingsKey: 'text-setting-4',
                title: 'A text setting for doubles only',
                keyboardType: TextInputType.number,
              ),
            ],
          ),
          MultiSelectSetting<String>(
            settingsKey: 'multi-select-setting',
            title: "A multi-select setting",
            items: [
              ListItem(value: "hello", caption: "Hello"),
              ListItem(value: "world", caption: "World"),
              ListItem(value: "foo", caption: "foo"),
              ListItem(value: "bar", caption: "bar"),
            ]
          ),
          RadioModalSetting<int>(
            settingsKey: 'radio-modal-setting',
            title: 'This is a modal radio setting',
            defaultValue: 5,
            items: [
              ListItem<int>(value: 1, caption: 'One'),
              ListItem<int>(value: 2, caption: 'Two'),
              ListItem<int>(value: 3, caption: 'Three'),
              ListItem<int>(value: 4, caption: 'Four'),
              ListItem<int>(value: 5, caption: 'Five'),
              ListItem<int>(value: 6, caption: 'Six'),
              ListItem<int>(value: 7, caption: 'Seven'),
              ListItem<int>(value: 8, caption: 'Eight'),
              ListItem<int>(value: 9, caption: 'Nine'),
              ListItem<int>(value: 10, caption: 'Ten'),
              ListItem<int>(value: 11, caption: 'Eleven'),
              ListItem<int>(value: 12, caption: 'Twelve'),
              ListItem<int>(value: 13, caption: 'Thirteen'),
              ListItem<int>(value: 14, caption: 'Fourteen'),
              ListItem<int>(value: 15, caption: 'Fifteen'),
              ListItem<int>(value: 16, caption: 'Sixteen'),
              ListItem<int>(value: 17, caption: 'Seventeen'),
              ListItem<int>(value: 18, caption: 'Eighteen'),
              ListItem<int>(value: 19, caption: 'Nineteen'),
              ListItem<int>(value: 20, caption: 'Twenty'),
              ListItem<int>(value: 21, caption: 'Twentyone'),
              ListItem<int>(value: 22, caption: 'Twentytwo'),
              ListItem<int>(value: 23, caption: 'Twentythree'),
            ],
          ),
          RadioSetting<int>(
            settingsKey: 'radio-setting',
            title: 'This is a radio setting',
            items: [
              ListItem<int>(value: 1, caption: 'One'),
              ListItem<int>(value: 2, caption: 'Two'),
              ListItem<int>(value: 3, caption: 'Three'),
              ListItem<int>(value: 4, caption: 'Four'),
              ListItem<int>(value: 5, caption: 'Five'),
            ]
          ),
          SliderSetting(
            settingsKey: 'slider-setting',
            title: 'This is a slider setting',
            minValue: 0.0,
            maxValue: 10.0,
            divisions: 10,
            defaultValue: 5.0,
          ),
          TestTypeSetting(
            title: "This is a settign with a custom type",
            settingsKey: "test-type-setting",
          ),
          CustomSetting(
            title: 'This is a custom setting',
            onPressed: () => showDialog(
              context: context,
              builder: (_) => AlertDialog(
                title: Text('Warning'),
                content: Text('Self destruct in 5 seconds.'),
                actions: <Widget>[
                  TextButton(
                    child: Text('Cancel'),
                    onPressed: () => Navigator.pop(context)
                  ),
                  TextButton(
                    child: Text('OK'),
                    onPressed: () => Navigator.pop(context)
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter应用中使用cobi_flutter_settings插件进行设置管理的代码示例。cobi_flutter_settings插件允许你轻松地在Flutter应用中管理应用设置。

步骤1:添加依赖

首先,你需要在pubspec.yaml文件中添加cobi_flutter_settings依赖:

dependencies:
  flutter:
    sdk: flutter
  cobi_flutter_settings: ^latest_version  # 请使用最新版本号

然后运行flutter pub get来获取依赖。

步骤2:初始化设置管理

在你的Flutter应用的入口文件(通常是main.dart)中,初始化设置管理。

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

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

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

class SettingsInitializer extends StatefulWidget {
  final Widget child;

  SettingsInitializer({required this.child});

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

class _SettingsInitializerState extends State<SettingsInitializer> {
  @override
  void initState() {
    super.initState();
    // 初始化设置,这里可以加载默认设置或者从持久化存储中加载设置
    Settings.init(
      (key, value) async {
        // 当设置改变时的回调,这里可以保存设置到持久化存储
        print("Setting $key changed to $value");
      },
      defaultSettings: {
        'theme_mode': 'light', // 默认主题模式
        'sound_enabled': true, // 默认声音是否开启
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

步骤3:使用设置管理

现在你可以在你的应用中读取和设置配置选项了。下面是一个简单的示例,展示如何在一个页面中读取和修改设置。

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

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

class _MyHomePageState extends State<MyHomePage> {
  bool _soundEnabled = false;
  String _themeMode = '';

  @override
  void initState() {
    super.initState();
    // 监听设置变化
    Settings.addListener(updateSettings);
    // 初始化设置值
    updateSettings();
  }

  @override
  void dispose() {
    // 移除监听器
    Settings.removeListener(updateSettings);
    super.dispose();
  }

  void updateSettings() {
    setState(() {
      _soundEnabled = Settings.getBool('sound_enabled') ?? false;
      _themeMode = Settings.getString('theme_mode') ?? 'light';
    });
  }

  void toggleSound() {
    Settings.setBool('sound_enabled', !_soundEnabled);
  }

  void changeThemeMode(String newMode) {
    Settings.setString('theme_mode', newMode);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SwitchListTile(
              title: Text('Sound Enabled'),
              value: _soundEnabled,
              onChanged: toggleSound,
            ),
            ListTile(
              title: Text('Theme Mode'),
              subtitle: Text(_themeMode),
              trailing: DropdownButton<String>(
                value: _themeMode,
                icon: Icon(Icons.arrow_downward),
                iconSize: 24,
                elevation: 16,
                style: TextStyle(color: Colors.deepPurple),
                onChanged: changeThemeMode,
                items: ['light', 'dark'].map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

总结

上述代码展示了如何使用cobi_flutter_settings插件在Flutter应用中管理应用设置。你可以根据需要扩展和修改这些代码来满足你的特定需求。

回到顶部