Flutter设置管理插件fastyle_settings的使用

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

Flutter设置管理插件fastyle_settings的使用

fastyle_settings 是一套用于 fastyle 库的设置小部件。

完整示例代码

// Flutter imports:
import 'package:flutter/material.dart';

// Package imports:
import 'package:easy_localization/easy_localization.dart';
import 'package:fastyle_core/fastyle_core.dart';
import 'package:fastyle_pricing/fastyle_pricing.dart';
import 'package:fastyle_settings/fastyle_settings.dart';
import 'package:go_router/go_router.dart';
import 'package:lingua_core/generated/locale_keys.g.dart';
import 'package:lingua_core/lingua_core.dart';
import 'package:lingua_finance/generated/codegen_loader.g.dart';
import 'package:lingua_finance_instrument/generated/codegen_loader.g.dart';
import 'package:lingua_languages/generated/codegen_loader.g.dart';
import 'package:lingua_purchases/generated/codegen_loader.g.dart';
import 'package:lingua_settings/generated/codegen_loader.g.dart';
import 'package:lingua_settings/generated/locale_keys.g.dart';
import 'package:lingua_share/generated/codegen_loader.g.dart';

// 项目导入:
import './routes.dart';

final kAppInfo = kFastAppInfo.copyWith(
  appName: 'Fastyle Settings',
  databaseVersion: 0,
  supportedLocales: const [
    Locale('de'),
    Locale('en'),
    Locale('fr'),
    Locale('es'),
    Locale('it'),
    Locale('ja'),
    Locale('pt'),
    Locale('ru'),
    Locale('zh'),
  ],
);

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return FastApp(
      appInformation: kAppInfo,
      routesForMediaType: (mediaType) => [
        ...kAppRoutes,
        GoRoute(
          path: '/',
          builder: (_, __) => buildHome(context),
        ),
      ],
      assetLoader: LinguaLoader(
        mapLocales: LinguaLoader.mergeMapLocales([
          SettingsCodegenLoader.mapLocales,
          LanguagesCodegenLoader.mapLocales,
          FinanceCodegenLoader.mapLocales,
          FinanceInstrumentCodegenLoader.mapLocales,
          ShareCodegenLoader.mapLocales,
          PurchasesCodegenLoader.mapLocales,
        ]),
      ),
    );
  }

  Widget buildHome(BuildContext context) {
    return FastAppInfoPage<String>(
      titleText: SettingsLocaleKeys.settings_label_app_settings.tr(),
      showAppBar: false,
      header: FastPremiumSettingsHeader(
        premiumProductId: 'premium',
        onGoPremium: () {
          debugPrint('Go premium');
        },
      ),
      categoryDescriptors: [
        FastNavigationCategoryDescriptor(
          titleText: SettingsLocaleKeys.settings_label_app_settings.tr(),
          items: [
            FastSettingsItem.getItem(context, FastSettingsItems.appearance),
            FastSettingsItem.getItem(context, FastSettingsItems.language),
            FastSettingsItem.getItem(context, FastSettingsItems.calculator),
          ],
        ),
        FastNavigationCategoryDescriptor(
          titleText: SettingsLocaleKeys.settings_label_customer_support.tr(),
          items: [
            FastSettingsItem.getItem(context, FastSettingsItems.contactUs),
            FastSettingsItem.getItem(context, FastSettingsItems.bugReport),
          ],
        ),
        FastNavigationCategoryDescriptor(
          titleText: SettingsLocaleKeys.settings_label_legal.tr(),
          items: [
            FastSettingsItem.getItem(context, FastSettingsItems.privacyPolicy),
            FastSettingsItem.getItem(context, FastSettingsItems.termsOfService),
            FastSettingsItem.getItem(context, FastSettingsItems.disclaimer),
          ],
        ),
        FastNavigationCategoryDescriptor(
          titleText: 'Fastyle',
          items: [
            FastSettingsItem.getItem(context, FastSettingsItems.share),
            FastSettingsItem.getItem(context, FastSettingsItems.rateUs),
          ],
        ),
        FastNavigationCategoryDescriptor(
          titleText: CoreLocaleKeys.core_label_follow_us.tr(),
          items: [
            FastSettingsItem.getItem(context, FastSettingsItems.website),
            FastSettingsItem.getItem(context, FastSettingsItems.twitter),
            FastSettingsItem.getItem(context, FastSettingsItems.facebook),
          ],
        ),
      ],
    );
  }
}

代码说明

  1. 导入包:

    import 'package:flutter/material.dart';
    import 'package:easy_localization/easy_localization.dart';
    import 'package:fastyle_core/fastyle_core.dart';
    import 'package:fastyle_pricing/fastyle_pricing.dart';
    import 'package:fastyle_settings/fastyle_settings.dart';
    import 'package:go_router/go_router.dart';
    import 'package:lingua_core/generated/locale_keys.g.dart';
    import 'package:lingua_core/lingua_core.dart';
    import 'package:lingua_finance/generated/codegen_loader.g.dart';
    import 'package:lingua_finance_instrument/generated/codegen_loader.g.dart';
    import 'package:lingua_languages/generated/codegen_loader.g.dart';
    import 'package:lingua_purchases/generated/codegen_loader.g.dart';
    import 'package:lingua_settings/generated/codegen_loader.g.dart';
    import 'package:lingua_settings/generated/locale_keys.g.dart';
    import 'package:lingua_share/generated/codegen_loader.g.dart';
    

    导入了必要的 Flutter 包和 fastyle 库中的相关组件。

  2. 初始化应用信息:

    final kAppInfo = kFastAppInfo.copyWith(
      appName: 'Fastyle Settings',
      databaseVersion: 0,
      supportedLocales: const [
        Locale('de'),
        Locale('en'),
        Locale('fr'),
        Locale('es'),
        Locale('it'),
        Locale('ja'),
        Locale('pt'),
        Locale('ru'),
        Locale('zh'),
      ],
    );
    

    初始化应用程序信息,包括应用名称、数据库版本和受支持的语言列表。

  3. 主函数:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      runApp(const MyApp());
    }
    

    确保 Flutter 绑定初始化,并运行 MyApp 应用程序。

  4. MyApp类:

    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return FastApp(
          appInformation: kAppInfo,
          routesForMediaType: (mediaType) => [
            ...kAppRoutes,
            GoRoute(
              path: '/',
              builder: (_, __) => buildHome(context),
            ),
          ],
          assetLoader: LinguaLoader(
            mapLocales: LinguaLoader.mergeMapLocales([
              SettingsCodegenLoader.mapLocales,
              LanguagesCodegenLoader.mapLocales,
              FinanceCodegenLoader.mapLocales,
              FinanceInstrumentCodegenLoader.mapLocales,
              ShareCodegenLoader.mapLocales,
              PurchasesCodegenLoader.mapLocales,
            ]),
          ),
        );
      }
    
      Widget buildHome(BuildContext context) {
        return FastAppInfoPage<String>(
          titleText: SettingsLocaleKeys.settings_label_app_settings.tr(),
          showAppBar: false,
          header: FastPremiumSettingsHeader(
            premiumProductId: 'premium',
            onGoPremium: () {
              debugPrint('Go premium');
            },
          ),
          categoryDescriptors: [
            FastNavigationCategoryDescriptor(
              titleText: SettingsLocaleKeys.settings_label_app_settings.tr(),
              items: [
                FastSettingsItem.getItem(context, FastSettingsItems.appearance),
                FastSettingsItem.getItem(context, FastSettingsItems.language),
                FastSettingsItem.getItem(context, FastSettingsItems.calculator),
              ],
            ),
            // 其他分类描述...
          ],
        );
      }
    }
    

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用fastyle_settings插件来管理设置的代码示例。fastyle_settings是一个用于管理应用设置的Flutter插件,它提供了一系列易于使用的组件来构建设置页面。

首先,确保你已经在pubspec.yaml文件中添加了fastyle_settings依赖:

dependencies:
  flutter:
    sdk: flutter
  fastyle_settings: ^最新版本号  # 请替换为最新的版本号

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

接下来,我们来看一个基本的示例,展示如何使用fastyle_settings来创建一个设置页面。

1. 创建一个设置模型

首先,我们需要定义一个设置模型。这通常是一个包含设置项及其当前值的类。

import 'package:fastyle_settings/fastyle_settings.dart';

class AppSettings {
  final Setting<bool> enableNotifications;
  final Setting<String> themeMode;

  AppSettings({
    required this.enableNotifications,
    required this.themeMode,
  });
}

2. 初始化设置

在你的主应用程序或某个初始化逻辑中,创建并初始化这些设置。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fastyle_settings/fastyle_settings.dart';
import 'app_settings.dart'; // 导入你创建的设置模型文件

void main() {
  final settings = AppSettings(
    enableNotifications: Setting<bool>(
      key: 'enable_notifications',
      defaultValue: true,
    ),
    themeMode: Setting<String>(
      key: 'theme_mode',
      defaultValue: 'light', // 假设你有'light'和'dark'两种主题模式
      options: ['light', 'dark'],
    ),
  );

  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => settings.enableNotifications),
        ChangeNotifierProvider(create: (_) => settings.themeMode),
      ],
      child: MyApp(settings: settings),
    ),
  );
}

class MyApp extends StatelessWidget {
  final AppSettings settings;

  MyApp({required this.settings});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Settings Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SettingsPage(settings: settings),
    );
  }
}

3. 创建设置页面

现在,我们来创建一个设置页面,使用fastyle_settings提供的组件来显示和编辑设置。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fastyle_settings/fastyle_settings.dart';
import 'app_settings.dart'; // 导入你创建的设置模型文件

class SettingsPage extends StatelessWidget {
  final AppSettings settings;

  SettingsPage({required this.settings});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SwitchSetting<bool>(
              setting: settings.enableNotifications,
              title: 'Enable Notifications',
            ),
            DropdownSetting<String>(
              setting: settings.themeMode,
              title: 'Theme Mode',
              hint: 'Select your theme mode',
            ),
          ],
        ),
      ),
    );
  }
}

4. 处理设置更改

由于我们使用了Provider来管理设置状态,当用户在界面上更改设置时,Provider会自动通知相关的监听器。你可以在任何需要的地方监听这些更改,并应用相应的逻辑。

例如,监听主题模式的更改并应用新的主题:

class MyApp extends StatelessWidget {
  final AppSettings settings;

  MyApp({required this.settings});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        // ... 其他providers
        ChangeNotifierProvider<Setting<String>>(
          create: (_) => settings.themeMode,
          listen: false, // 因为我们在其他地方手动监听
          child: Consumer<Setting<String>>(
            builder: (context, themeMode, child) {
              final theme = themeMode.value == 'dark'
                  ? ThemeData.dark()
                  : ThemeData.light();

              return MaterialApp(
                title: 'Flutter Settings Example',
                theme: theme,
                home: SettingsPage(settings: settings),
              );
            },
          ),
        ),
      ],
      child: Consumer<Setting<bool>>( // 监听通知设置
        builder: (context, enableNotifications, child) {
          // 在这里处理通知设置的更改
          return child!;
        },
      ),
    );
  }
}

注意:上述代码中的MultiProvider结构可能需要根据你的实际需求进行调整,因为将所有providers放在一个MultiProvider中可能会导致结构过于复杂。你可以根据需要将providers分散到不同的widget树层级中。

以上就是一个使用fastyle_settings插件来管理Flutter应用设置的完整示例。希望这对你有所帮助!

回到顶部