Flutter扩展功能插件awesome_flutter_extensions的使用
Flutter扩展功能插件awesome_flutter_extensions的使用
Awesome Flutter Extensions
Awesome flutter extensions to remove boilerplate
Installation
使用终端安装
flutter pub add awesome_flutter_extensions
在pubspec.yaml
中添加依赖
dependencies:
awesome_flutter_extensions: ^1.0.0 # Use the latest version from pub.dev
使用 Pubspec Assist (VSCode 插件)
- 打开命令面板:
- Mac: (⇧ ⌘ P)
- Windows: (Ctrl ⇧ P)
- 输入
Pubspec assist..
直到出现Pubspec Assist: Add/Update dependencies
. - 输入包名
awesome_flutter_extensions
并按下 ENTER ↵.
Get Started
首先,导入扩展库:
import 'package:awesome_flutter_extensions/awesome_flutter_extensions.dart';
Usage
这个库中的扩展被分为多个组,包括:sizes、textStyles、colors、themes、platform、string、navigator 和 miscellaneous。
Sizes
获取屏幕宽度:
// before
MediaQuery.sizeOf(context).width
// after
context.sizes.width;
所有可用的扩展:
- width
- maybeWidth
- height
- maybeHeight
- padding
- maybePadding
- viewInsets
- maybeViewInsets
- systemGestureInsets
- maybeSystemGestureInsets
- viewPadding
- maybeViewPadding
- devicePixelRatio
- maybeDevicePixelRatio
- textScaler
- maybeTextScaler
添加padding:
// before
Padding(padding: EdgeInsets.symmetric(horizontal: 16))
// now
Padding(padding: 16.paddingHorizontal())
所有可用的EdgeInsets:
- paddingAll
- paddingHorizontal
- paddingVertical
- paddingTop
- paddingLeft
- paddingRight
- paddingBottom
TextStyles
获取标题大文本样式:
// before
Theme.of(context).textTheme.titleLarge!
// after
context.textStyles.titleLarge
所有可用的扩展:
- displayLarge
- displayMedium
- displaySmall
- headlineLarge
- headlineMedium
- headlineSmall
- titleLarge
- titleMedium
- titleSmall
- bodyLarge
- bodyMedium
- bodySmall
- labelLarge
- labelMedium
- labelSmall
更改字体粗细:
context.textStyles.titleLarge.semiBold
所有可用的字体粗细:
- thick
- extraBold
- bold
- semiBold
- medium
- regular
- light
- extraLight
- thin
更改字体样式:
context.textStyles.titleLarge.italic
所有可用的字体样式:
- normal
- italic
Colors
从主题中获取主颜色:
// before
Theme.of(context).primaryColor
// after
context.colors.primary
获取颜色方案的颜色:
// before
Theme.of(context).colorScheme
// after
context.colors.scheme
所有可用的扩展:
- primary
- primaryLight
- primaryDark
- canvas
- scaffoldBackground
- card
- divider
- focus
- hover
- highlight
- splash
- unselectedWidget
- disabled
- secondaryHeader
- dialogBackground
- indicator
- hint
- shadow
- scheme
Themes
获取应用栏主题:
// before
Theme.of(context).appBarTheme
// after
context.themes.appBar;
所有可用的扩展:
- button
- toggleButtons
- text
- primaryText
- inputDecoration
- icon
- primaryIcon
- slider
- tabBar
- tooltip
- card
- chip
- appBar
- scrollbar
- bottomAppBar
- dialog
- floatingActionButton
- navigationRail
- cupertinoOverride
- snackBar
- bottomSheet
- popupMenu
- banner
- divider
- buttonBar
- bottomNavigationBar
- timePicker
- textButton
- elevatedButton
- outlinedButton
- textSelection
- dataTable
- checkbox
- radio
- switchTheme
- badge
- drawer
- dropdownMenu
- expansionTile
- extensions
- filledButton
- iconButton
- listTile
- menu
- menuBar
- menuButton
- navigationBar
- navigationDrawer
- pageTransitions
- progressIndicator
- segmentedButton
Platform
检测应用程序运行的平台:
final isMacOS = context.platform.isMacOS
所有可用参数:
- isAndroid
- isWeb
- isMacOS
- isWindows
- isFuchsia
- isIOS
- isLinux
检测目标平台(例如,应用程序在Web上运行,但来自iOS设备):
final isIOS = context.targetPlatform.isIOS;
所有可用参数:
- isAndroid
- isFuchsia
- isIOS
- isLinux
- isMacOS
- isWindows
String
字符串的各种扩展,例如:
首字母大写
final s = 'hello world';
print(s.capitalizeFirst()); // Hello world
每个单词首字母大写
final s = 'hello world';
print(s.capitalize()); // Hello World
Mock word
final s = 'hello world';
print(s.mock); // hello world 🧨
判断是否为数字
final s = '2.0';
print(s.isNum()); // true
final s2 = 'hi';
print(s2.isNum()); // false
所有可用的扩展:
- capitalize
- capitalizeFirst
- mock
- isBool(caseSensitive = true)
- toBool(caseSensitive = true)
- isNum
- toNum
- isDouble
- toDouble
- inInt
- toInt
- removeAllWhitespace
- hasMatch
Miscellaneous
记录对象
// before
import 'dart:developer' as devtools show log;
devtools.log(MyClass.toString());
// now
MyClass.log();
分隔Column或Row
// before
Column(
children: [
FirstWidget(),
SizedBox(height: 8),
SecondWidget()
SizedBox(height: 8),
ThirdWidget(),
],
),
// now
Column(
children: [
FirstWidget(),
SecondWidget()
ThirdWidget(),
].separatedBy(SizedBox(height: 8)),
),
将数字转换为Duration
// before
final twoDays = Duration(days: 2);
// now
final twoDays = 2.days;
所有可用扩展:
- microseconds
- milliseconds
- seconds
- minutes
- hours
- days
- months
- quarters
- quadrimesters
- years
Future delayed
// before
await Future.delayed(Duration(seconds: 5));
// now
await 5.seconds.future();
Navigator
推送页面:
// before
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SecondPage(),
),
);
// after
context.navigator.push(
MaterialPageRoute(
builder: (context) => const SecondPage(),
),
);
// or even shorter
context.navigator.pushMaterial(const SecondPage()),
所有可用扩展:
- canPop
- maybePop
- pop
- popUntil
- push
- pushMaterial
- pushCupertino
- popAndPushNamed
- pushAndRemoveUntil
- pushNamed
- pushNamedAndRemoveUntil
- pushReplacement
- pushReplacementMaterial
- pushReplacementCupertino
- pushReplacementNamed
- removeRoute
- removeRouteBelow
- replace
- replaceRouteBelow
示例代码
以下是一个简单的示例,展示了如何使用 awesome_flutter_extensions
创建一个Flutter应用程序:
import 'package:flutter/material.dart';
import 'package:awesome_flutter_extensions/awesome_flutter_extensions.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
fontFamily: 'Roboto',
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key? key, required this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
style: context.textStyles.bodyLarge.bold,
),
Text(
'0',
style: context.textStyles.headlineMedium.bold,
),
],
).paddingSymmetric(vertical: 16),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
);
}
}
在这个示例中,我们使用了 awesome_flutter_extensions
的一些特性,如 context.textStyles
和 paddingSymmetric
。希望这个示例能帮助你更好地理解如何使用该库。
更多关于Flutter扩展功能插件awesome_flutter_extensions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter扩展功能插件awesome_flutter_extensions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用awesome_flutter_extensions
插件的一个简单示例。这个插件提供了一系列有用的扩展功能,可以帮助开发者更轻松地实现一些常见的功能。
首先,你需要在你的pubspec.yaml
文件中添加这个依赖项:
dependencies:
flutter:
sdk: flutter
awesome_flutter_extensions: ^最新版本号 # 请替换为实际最新版本号
然后,运行flutter pub get
来安装这个依赖项。
以下是一个简单的Flutter应用示例,展示了如何使用awesome_flutter_extensions
中的一些功能,比如获取设备信息、显示Toast消息等。
main.dart
import 'package:flutter/material.dart';
import 'package:awesome_flutter_extensions/awesome_flutter_extensions.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Awesome Flutter Extensions Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String deviceInfo = '';
@override
void initState() {
super.initState();
_getDeviceInfo();
}
Future<void> _getDeviceInfo() async {
try {
DeviceInfo deviceInfoResult = await DeviceInfoPlugin().deviceInfo;
setState(() {
deviceInfo = "Device Name: ${deviceInfoResult.deviceName}\n"
"Device Model: ${deviceInfoResult.model}\n"
"Device Version: ${deviceInfoResult.version}\n"
"Platform: ${deviceInfoResult.platform}";
});
} catch (e) {
print(e);
}
}
void _showToast() {
Toast.show("Hello, this is a toast message!", context,
duration: Toast.LENGTH_SHORT,
gravity: Toast.BOTTOM,
backgroundColor: Colors.black.withOpacity(0.7),
textColor: Colors.white,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Awesome Flutter Extensions Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Device Info:', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
Text(deviceInfo, style: TextStyle(fontSize: 16)),
SizedBox(height: 20),
ElevatedButton(
onPressed: _showToast,
child: Text('Show Toast Message'),
),
],
),
),
);
}
}
说明
- 添加依赖:在
pubspec.yaml
文件中添加awesome_flutter_extensions
依赖。 - 获取设备信息:使用
DeviceInfoPlugin().deviceInfo
来获取设备信息,并在UI中显示。 - 显示Toast消息:使用
Toast.show
方法显示一个Toast消息。
这个示例演示了如何使用awesome_flutter_extensions
中的两个主要功能。当然,awesome_flutter_extensions
插件提供了更多的功能,你可以根据项目的需要查阅其文档来进一步了解和使用其他功能。