Flutter卡片管理插件cardoteka的功能使用

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

Flutter卡片管理插件cardoteka的功能使用

Cardoteka简介

Cardoteka 是一个基于 SharedPreferences 的类型安全包装器。它提供了系统化的键和默认值存储方式,并且允许通过 getset 方法简化数据的存储和检索。

Cardoteka的优势

  1. 系统化存储:你的键和默认值被系统地存储,不需要考虑存放位置。
  2. 简化操作:使用 getset 方法替代多个 getBoolsetDouble 等方法。
  3. 状态更新:当新数据到达存储时,立即更新状态。
  4. 空值处理:频繁检查值是否为空?使用 getOrNullsetOrNull 方法。
  5. 动态访问:仍然需要访问原始库的动态方法?可以通过指定 with AccessToSP 实现。

如何使用?

1. 定义卡片

定义要存储的类型和默认值,并指定转换器(如果需要):

import 'package:cardoteka/cardoteka.dart';
import 'package:flutter/material.dart' hide Card;

enum SettingsCards<T extends Object> implements Card<T> {
   userColor(DataType.int, Color(0x00FF4BFF)),
   themeMode(DataType.string, ThemeMode.light),
   isPremium(DataType.bool, false),
   ;

   const SettingsCards(this.type, this.defaultValue);

   [@override](/user/override)
   final DataType type;

   [@override](/user/override)
   final T defaultValue;

   [@override](/user/override)
   String get key => name;

   static Map<SettingsCards, Converter> get converters => const {
      themeMode: EnumAsStringConverter(ThemeMode.values),
      userColor: Converters.colorAsInt,
   };
}
2. 定义存储并混合功能
class SettingsCardoteka extends Cardoteka with WatcherImpl {
  SettingsCardoteka({required super.config});
}
3. 初始化并使用功能
void main() async {
  // 如果在调用 runApp 之前进行绑定
  WidgetsFlutterBinding.ensureInitialized();

  await Cardoteka.init();
  final cardoteka = SettingsCardoteka(
    config: CardotekaConfig(
      name: 'settings',
      cards: SettingsCards.values,
      converters: SettingsCards.converters,
    ),
  );

  final log = StringBuffer('All notifications for SettingsCards.themeMode:\n');
  cardoteka.attach(
    SettingsCards.themeMode,
    (value) => log.writeln('-> $value'),
    onRemove: () => log.writeln('-> has been removed from storage'),
    detacher: (onDetach) {
      // 将 onDetach 传递给负责对象生命周期的对象
    },
  );

  ThemeMode themeMode = cardoteka.get(SettingsCards.themeMode);
  print(themeMode); // 返回默认值 -> ThemeMode.light

  await cardoteka.set(SettingsCards.themeMode, ThemeMode.dark); // 第一次日志
  themeMode = cardoteka.get(SettingsCards.themeMode);
  print(themeMode); // ThemeMode.dark

  // 使用泛型防止传递不同类型参数时可能出现的错误
  await cardoteka.set<bool>(SettingsCards.isPremium, true);
  await cardoteka.set<Color>(SettingsCards.userColor, Colors.deepOrange);

  await cardoteka.remove(SettingsCards.themeMode); // 第二次日志
  Map<Card<Object?>, Object> storedEntries = cardoteka.getStoredEntries();
  print(storedEntries);
  // {
  //   SettingsCards.userColor: Color(0xffff5722),
  //   SettingsCards.isPremium: true
  // }

  await cardoteka.removeAll(); // 第三次日志
  storedEntries = cardoteka.getStoredEntries();
  print(storedEntries); // {}

  print(log); // All notifications for SettingsCards.themeMode:
  // -> ThemeMode.dark
  // -> has been removed from storage
  // -> has been removed from storage
}

示例代码

以下是完整的示例代码:

import 'package:cardoteka/cardoteka.dart';
import 'package:flutter/material.dart' hide Card;

enum SettingsCards<T extends Object> implements Card<T> {
  userColor(DataType.int, Color(0x00FF4BFF)),
  themeMode(DataType.string, ThemeMode.light),
  isPremium(DataType.bool, false),
  ;

  const SettingsCards(this.type, this.defaultValue);

  [@override](/user/override)
  final DataType type;

  [@override](/user/override)
  final T defaultValue;

  [@override](/user/override)
  String get key => name;

  static Map<SettingsCards, Converter> get converters => const {
        themeMode: EnumAsStringConverter(ThemeMode.values),
        userColor: Converters.colorAsInt,
      };
}

class SettingsCardoteka extends Cardoteka with WatcherImpl {
  SettingsCardoteka({required super.config});
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Cardoteka.init();
  final cardoteka = SettingsCardoteka(
    config: CardotekaConfig(
      name: 'settings',
      cards: SettingsCards.values,
      converters: SettingsCards.converters,
    ),
  );

  final log = StringBuffer('All notifications for SettingsCards.themeMode:\n');
  cardoteka.attach(
    SettingsCards.themeMode,
    (value) => log.writeln('-> $value'),
    onRemove: () => log.writeln('-> has been removed from storage'),
    detacher: (onDetach) {
      // pass onDetach to whoever is responsible for the lifetime of the object
    },
  );

  ThemeMode themeMode = cardoteka.get(SettingsCards.themeMode);
  print(themeMode); // will return default value -> ThemeMode.light

  await cardoteka.set(SettingsCards.themeMode, ThemeMode.dark); // first log
  themeMode = cardoteka.get(SettingsCards.themeMode);
  print(themeMode); // ThemeMode.dark

  await cardoteka.set<bool>(SettingsCards.isPremium, true);
  await cardoteka.set<Color>(SettingsCards.userColor, Colors.deepOrange);

  await cardoteka.remove(SettingsCards.themeMode); // second log
  Map<Card<Object?>, Object> storedEntries = cardoteka.getStoredEntries();
  print(storedEntries);
  // {
  //   SettingsCards.userColor: Color(0xffff5722),
  //   SettingsCards.isPremium: true
  // }

  await cardoteka.removeAll(); // third log
  storedEntries = cardoteka.getStoredEntries();
  print(storedEntries); // {}

  print(log); // All notifications for SettingsCards.themeMode:
  // -> ThemeMode.dark
  // -> has been removed from storage
  // -> has been removed from storage
}

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

1 回复

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


当然,作为IT专家,我可以为你提供一个关于如何使用Flutter卡片管理插件cardoteka的代码案例。请注意,cardoteka可能是一个假设的插件名称,因为在实际Flutter社区中并没有一个广泛认可的名为cardoteka的插件。不过,我可以根据卡片管理的通用功能来编写一个示例代码,展示如何在Flutter中实现类似的功能。

假设我们需要一个卡片管理功能,其中包括添加、删除和显示卡片。我们可以使用Flutter的内置组件和一些状态管理来实现这个功能。以下是一个简单的示例代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Card Management',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: CardManager(),
    );
  }
}

class CardManager extends StatefulWidget {
  @override
  _CardManagerState createState() => _CardManagerState();
}

class _CardManagerState extends State<CardManager> {
  final List<String> _cards = [];

  void _addCard() {
    setState(() {
      _cards.add('Card ${_cards.length + 1}');
    });
  }

  void _removeCard(String card) {
    setState(() {
      _cards.remove(card);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Card Manager'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: _addCard,
            tooltip: 'Add Card',
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: ListView.builder(
          itemCount: _cards.length,
          itemBuilder: (BuildContext context, int index) {
            final String card = _cards[index];
            return Card(
              child: ListTile(
                leading: Icon(Icons.label),
                title: Text(card),
                trailing: IconButton(
                  icon: Icon(Icons.delete),
                  onPressed: () => _removeCard(card),
                ),
                onTap: () {
                  // Handle card tap if needed
                },
              ),
            );
          },
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的卡片管理应用:

  1. MyApp:这是应用的入口点,它定义了应用的主题和主页。

  2. CardManager:这是一个有状态的组件,用于管理卡片列表的状态。

  3. _CardManagerState:这是CardManager的状态类,它包含了卡片列表_cards以及添加和删除卡片的方法。

  4. 添加卡片:在AppBar的右侧,我们添加了一个IconButton,当用户点击它时,会调用_addCard方法向卡片列表中添加一个新卡片。

  5. 删除卡片:在每个卡片上,我们添加了一个IconButton,当用户点击它时,会调用_removeCard方法从卡片列表中删除该卡片。

  6. 显示卡片:我们使用ListView.builder来动态生成卡片列表,并根据列表的长度来渲染卡片。

这个示例代码展示了如何在Flutter中实现卡片管理的基本功能。如果你有一个具体的cardoteka插件,并且它有特定的API或功能,你可能需要根据该插件的文档来调整这个示例代码。

回到顶部