Flutter核心样式管理插件fastyle_core的使用
Flutter核心样式管理插件fastyle_core的使用
fastyle_core
是 fastyle
库的核心包。它提供了基础的样式管理和主题切换功能。
示例代码
以下是使用 fastyle_core
的完整示例代码:
// Flutter imports:
import 'package:fastyle_buttons/fastyle_buttons.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
// Package imports:
import 'package:fastyle_core/fastyle_core.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:t_helpers/helpers.dart';
// Project imports:
import 'package:fastyle_core_example/data/items.dart';
import 'package:fastyle_core_example/routes.dart';
// 定义一个加载任务类
class DummyLoaderJob extends FastJob {
[@override](/user/override)
Future<void> initialize(
BuildContext context, {
IFastErrorReporter? errorReporter,
}) {
return Future.delayed(const Duration(milliseconds: 500));
}
}
// 定义一个会抛出错误的加载任务类
class DummyCrashLoaderJob extends FastJob {
[@override](/user/override)
Future<void> initialize(
BuildContext context, {
IFastErrorReporter? errorReporter,
}) async {
await Future.delayed(const Duration(milliseconds: 250));
throw ErrorDescription('Demo');
}
}
void main() {
GoogleFonts.config.allowRuntimeFetching = false;
runApp(const MyApp());
}
// 主应用类
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return FastApp(
// 设置浅色和深色主题
lightTheme: FastTheme.light.blue,
darkTheme: FastTheme.dark.blue,
// 定义路由
routesForMediaType: (mediaType) => [
...kAppRoutes,
GoRoute(path: '/', builder: (_, __) => const MyHomePage()),
],
// 添加加载任务
loaderJobs: [
DummyLoaderJob(),
DummyLoaderJob(),
DummyLoaderJob(),
// DummyCrashLoaderJob(),
DummyLoaderJob(),
],
// 错误构建器
errorBuilder: (context, error) {
final palette = ThemeHelper.getPaletteColors(context);
return Center(
child: FastBody(
// 设置文本颜色
textColor: palette.red.mid,
text: 'Oops! An error occurred while launching the app',
),
);
},
// 加载进度条构建器
loaderBuilder: (context, progress) {
debugPrint(progress.toString());
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FastLinearProgressBarIndicator(
// 显示进度标签和百分比
showProgressLabel: true,
showAsPercentage: true,
fractionDigits: 0,
minBarHeight: 20,
value: progress,
barRadius: 10,
maxValue: 1,
),
kFastSizedBox16,
const FastBody(
text: 'Please wait while the application is loading...',
),
],
);
},
);
}
}
// 主页面类
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
[@override](/user/override)
MyHomePageState createState() => MyHomePageState();
}
// 主页面状态类
class MyHomePageState extends State<MyHomePage> {
[@override](/user/override)
Widget build(BuildContext context) {
final palette = ThemeHelper.getPaletteColors(context);
return FastHomePage(
// 设置主页面头部图标按钮
leading: FastIconButton2(
onTap: () => context.go('/onboarding'),
icon: const Icon(Icons.account_circle),
iconColor: palette.whiteColor,
iconSize: kFastIconSizeMedium,
),
// 设置主页面顶部操作按钮
actions: [
FastIconButton2(
onTap: () async {
final response = await Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => const FastSearchPage(
items: demoItems,
categories: demoCategories,
groupByCategory: true,
useFuzzySearch: true,
),
fullscreenDialog: true,
),
);
if (response != null) {
debugPrint(response.value.toString());
}
},
icon: const Icon(Icons.search),
iconColor: palette.whiteColor,
iconSize: kFastIconSizeMedium,
),
],
// 设置主页面标题和副标题
titleText: 'Fastyle Demo',
subtitleText: 'Hello stranger! Have a wonderful day! :)',
// 设置浮动按钮
floatingActionButton: const FloatingActionButton(
onPressed: noop,
tooltip: 'Settings',
child: Icon(Icons.settings),
),
// 构建列表项
children: _buildList(context),
);
}
// 构建列表项的方法
List<Widget> _buildList(BuildContext context) {
final themeBloc = FastThemeBloc.instance;
final palette = ThemeHelper.getPaletteColors(context);
return [
const FastListHeader(
categoryText: 'options',
captionText: 'Favorites',
),
FastToggleListItem(
// 切换深色模式的开关
leading: const Icon(Icons.brightness_2),
labelText: 'Dark Mode',
isChecked: themeBloc.currentState.brightness == Brightness.dark,
onValueChanged: (bool shouldSwitchToDarkMode) {
if (shouldSwitchToDarkMode) {
themeBloc.addEvent(const FastThemeBlocEvent.dark());
} else {
themeBloc.addEvent(const FastThemeBlocEvent.light());
}
},
),
const FastListHeader(
categoryText: 'ui categories',
),
FastNavigationListItem(
// 导航到按钮页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.radio_button_checked),
palette: palette.purple,
),
labelText: 'Buttons',
descriptionText: 'Raised, icon buttons',
onTap: () => context.go('/buttons'),
),
FastNavigationListItem(
// 导航到字体页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.text_fields),
palette: palette.green,
),
labelText: 'Typography',
descriptionText: 'Title, subhead...',
onTap: () => context.go('/typography'),
),
FastNavigationListItem(
// 导航到标签页页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.table_chart),
palette: palette.blue,
),
labelText: 'Tabs',
onTap: () => context.go('/tabs'),
),
FastNavigationListItem(
// 导航到卡片页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.view_agenda),
palette: palette.blueGray,
),
labelText: 'Cards',
onTap: () => context.go('/cards'),
),
FastNavigationListItem(
// 导航到列表页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.view_list),
palette: palette.pink,
),
labelText: 'List',
onTap: () => context.go('/list'),
),
FastNavigationListItem(
// 导航到字段页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.edit),
palette: palette.teal,
),
labelText: 'Fields',
onTap: () => context.go('/fields'),
),
FastNavigationListItem(
// 导航到通知页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.message),
palette: palette.orange,
),
labelText: 'Notifications',
onTap: () => context.go('/notifications'),
),
FastNavigationListItem(
// 导航到颜色页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.colorize),
palette: palette.red,
),
labelText: 'Colors',
onTap: () => context.go('/colors'),
),
FastNavigationListItem(
// 导航到页面页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.description),
palette: palette.brown,
),
labelText: 'Page',
onTap: () => context.go('/page'),
),
FastNavigationListItem(
// 导航到响应式页面
leading: FastRoundedDuotoneIcon(
icon: const Icon(Icons.dashboard),
palette: palette.yellow,
),
labelText: 'responsive',
onTap: () => context.go('/responsive'),
),
FastNavigationListItem(
// 导航到拆分视图页面
leading: FastRoundedDuotoneIcon(
icon: const FaIcon(FontAwesomeIcons.tableColumns),
palette: palette.blue,
),
labelText: 'Split View',
onTap: () => context.go('/split-view'),
),
FastNavigationListItem(
// 导航到导航栏视图页面
leading: FastRoundedDuotoneIcon(
icon: const FaIcon(FontAwesomeIcons.tablet),
palette: palette.green,
),
labelText: 'Navigation Bar View',
onTap: () => context.go('/navigation-bar-view/explore'),
),
FastNavigationListItem(
// 导航到结果页面
leading: FastRoundedDuotoneIcon(
icon: const FaIcon(FontAwesomeIcons.triangleExclamation),
palette: palette.green,
),
labelText: 'Results',
onTap: () => context.go('/results'),
),
FastNavigationListItem(
// 导航到指示器页面
leading: FastRoundedDuotoneIcon(
icon: const FaIcon(FontAwesomeIcons.spinner),
palette: palette.blue,
),
labelText: 'Indicators',
onTap: () => context.go('/indicators'),
),
];
}
}
更多关于Flutter核心样式管理插件fastyle_core的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter核心样式管理插件fastyle_core的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用 fastyle_core
插件进行Flutter核心样式管理的代码示例。fastyle_core
是一个假设的插件名,用于说明目的,实际中你需要替换为具体的样式管理插件,例如 provider
、flutter_hooks
结合 useState
或者 flutter_bloc
等流行的状态管理库。由于 fastyle_core
不是实际存在的Flutter插件,下面的代码示例将展示如何使用 provider
插件进行样式管理。
1. 添加依赖
首先,在你的 pubspec.yaml
文件中添加 provider
依赖:
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0 # 确保版本是最新的
2. 创建主题数据类
创建一个 ThemeData
的封装类,以便我们可以更容易地管理主题:
import 'package:flutter/material.dart';
class AppTheme {
final Color primaryColor;
final Color secondaryColor;
final Color backgroundColor;
final TextTheme textTheme;
AppTheme({
required this.primaryColor,
required this.secondaryColor,
required this.backgroundColor,
required this.textTheme,
});
ThemeData toThemeData() {
return ThemeData(
primaryColor: primaryColor,
accentColor: secondaryColor,
scaffoldBackgroundColor: backgroundColor,
textTheme: textTheme,
);
}
}
3. 创建主题提供器
使用 ChangeNotifierProvider
来创建和管理主题提供器:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'app_theme.dart';
class ThemeNotifier with ChangeNotifier {
AppTheme _theme = AppTheme(
primaryColor: Colors.blue,
secondaryColor: Colors.teal,
backgroundColor: Colors.white,
textTheme: TextTheme(
bodyText1: TextStyle(color: Colors.black),
),
);
AppTheme get theme => _theme;
void changeTheme(AppTheme newTheme) {
_theme = newTheme;
notifyListeners();
}
}
4. 在应用入口使用主题提供器
在你的 main.dart
文件中,使用 MultiProvider
来提供 ThemeNotifier
:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_notifier.dart';
import 'app_theme.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => ThemeNotifier()),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ContextRead<ThemeNotifier>().theme.toThemeData(),
home: HomeScreen(),
);
}
}
class ContextRead<T> {
T read() {
return Provider.of<T>(context, listen: false);
}
}
extension BuildContextExtension on BuildContext {
T read<T>() {
return Provider.of<T>(this, listen: false);
}
}
注意:ContextRead
类和扩展是为了简化 Provider.of<T>(context, listen: false)
的调用,但这不是必要的,你可以直接使用 Provider.of<T>(context, listen: false)
。
5. 使用主题
在你的 HomeScreen
或其他屏幕中,你可以使用从 Provider
获取的主题:
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = context.read<ThemeNotifier>().theme;
return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
backgroundColor: theme.primaryColor,
),
body: Center(
child: Text(
'Hello, Flutter!',
style: theme.textTheme.bodyText1,
),
),
);
}
}
总结
以上代码展示了如何使用 provider
插件在Flutter应用中管理核心样式。虽然 fastyle_core
是一个假设的插件名,但这种方法可以应用于任何状态管理库,只需要根据具体库的API进行相应调整。希望这对你有所帮助!