Flutter 项目常用插件记录
#Flutter 2025/03/28 16:29:18
应用图标生成
flutter_launcher_icons | Dart package
flutter pub add flutter_launcher_icons
通过在 pubspec.yaml 文件中配置 flutter_launcher_icons 信息,运行 dart run launcher_icons
生成多平台应用图标。
flutter_launcher_icons:
image_path: 'lib/assets/icon/icon.jpg'
# ^0.14.2 遇到头像空白的 bug,添加 adaptive 两项
# [app icon not display black display #Android 15 · GitHub](https://github.com/fluttercommunity/flutter_launcher_icons/issues/618)
adaptive_icon_background: '#ffffff'
adaptive_icon_foreground: 'lib/assets/icon/icon.jpg'
android: true
ios: true
min_sdk_android: 21 # android min sdk min:16, default 21
web:
generate: true
image_path: 'lib/assets/icon/icon.jpg'
background_color: '#hexcode'
theme_color: '#hexcode'
windows:
generate: true
image_path: 'lib/assets/icon/icon.jpg'
icon_size: 48 # min:48, max:256, default: 48
macos:
generate: true
image_path: 'lib/assets/icon/icon.jpg'
Splash 开屏
flutter_native_splash | Flutter package
flutter pub add flutter_native_splash
通过在 pubspec.yaml 文件中配置 flutter_native_splash 信息,通过运行 dart run flutter_native_splash:create
生成多平台的 Splash 图片。
flutter_native_splash:
color: '#000000'
image: 'assets/images/logo.png'
web: false
国际化
Internationalizing Flutter apps
flutter pub add flutter_localizations --sdk=flutter
flutter pub add intl:any
return const MaterialApp(
title: 'Localizations Sample App',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
Locale('en'), // English
Locale('es'), // Spanish
],
home: MyHomePage(),
);
DateFormat.yMMMMd("en_US").format("2022-01-01"); // intl 格式化日期
屏幕适配工具
flutter_screenutil | Flutter package
@override
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: const Size(360, 690),
minTextAdapt: true,
builder: (context, child) {
return MaterialApp();
}
)
}
0.2.sw //屏幕宽度的 0.2 倍
0.5.sh //屏幕高度的 50%
Container(
width: 100.w, // .w 宽
height: 100.h, // .h 长
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(33.r) // .r 圆角
),
child: Text("111",style: TextStyle(fontSize: 20.sp)) // .sp 字体
)
状态管理工具
// 定义 User Provider
class UserProvider extends ChangeNotifier {
UserModel? _user;
UserModel? get user => _user;
void updateUser(UserModel user) {
_user = user;
notifiListeners();
}
}
// 注入 Provider
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => UserProvider(),
)
]
)
// 使用 Provider
// listen 为 true 时,状态变化会更新 Widget,false 适合用来调用方法。
final user = Provider.of<UserProvider>(context, listen: true).user;
Provider.of<UserProvider>(context, listen: false).updateUser(user);
坐标位置转换
纠正 Google 地图在中国区域内的坐标偏差。
LatLng getMapLocation(Position position) {
if (position.latitude >= 18.0 &&
position.latitude <= 53.0 &&
position.longitude >= 73.0 &&
position.longitude <= 135.0) {
print("you are in china");
final chinaGCJ = CoordTransform.transformWGS84toGCJ02(
position.longitude, position.latitude);
return LatLng(chinaGCJ.lat, chinaGCJ.lon);
} else {
return LatLng(position.latitude, position.longitude);
}
}
Firebase 集成
-
Firebase 基本配置
# 1.用于登录 firebase npm install -g firebase-tools # 2.登录 firebase firebase login # 3.安装 flutter fire 命令行 dart pub global activate flutterfire_cli # 4.在项目中配置 Firebase # 该操作会帮你选择或创建 Firebase 账号下的 Firebase 项目,并在 Fluter 项目中生成 Firebase 配置文件 firebase_options.dart,配置 gradle 插件 flutterfire configure # 5.安装 核心插件 flutter pub add firebase_core # 6.配置 Firebase,在项目配置了 firebase 相关内容后,需要运行该命令以确保配置文件保持最新状态 flutterfire configure
-
Firebase Messaging 插件
flutter pub add firebase_messaging
Future<void> init() async { onMessageListen(); onMessageInitListen(); onMessageTapListen(); await FirebaseMessaging.instance.requestPermission( provisional: true, badge: true, sound: true, alert: true, ); FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) async { // upload fcm token }); // IOS 必须先获取 APNSToken,即使看起来并没有用到 if(Platform.isIOS) { String? apnsToken = await FirebaseMessaging.instance.getAPNSToken(); if (apnsToken == null) { await Future.delayed(Duration(seconds: 3)); apnsToken = await FirebaseMessaging.instance.getAPNSToken(); } } try { final fcmToken = await FirebaseMessaging.instance.getToken() // update fcm token } catch (e) { // } } // 前台消息 Future<void> onMessageListen() async { FirebaseMessaging.onMessage.listen((RemoteMessage message) { // }) } // APP 初次加载时,检测消息 Future<void> onMessageInitListen() async { FirebaseMessage.instance.getInitialMessage().then((RemoteMessage? message) async { final notification = FirebaseNotification.fromJson(message.data); }) } // 检测进入 APP 的点击消息 Future<void> onMessageTapListen() async { FirebaseMessaging.onMessageOpendApp.listen((RemoteMessage message) async { final notification = FirebaseNotification.fromJson(message.data); }); }
-
Firebase Crashlytics 插件
flutter pub add firebase_crashlytics && flutter pub add firebase_analytics flutterfire configure
WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); FlutterError.onError = (errorDetails) { FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails); }; // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics PlatformDispatcher.instance.onError = (error, stack) { FirebaseCrashlytics.instance.recordError(error, stack, fatal: true); return true; };
其他常用工具
- 环境文件 flutter_dotenv | Flutter package
- S3 上传 minio | Dart package
- 应用内消息弹出提醒 top_snackbar_flutter | Flutter package
- 第三方 App 分享 share_plus | Flutter package
- 相机插件,相比 google 的相机插件使用更简单 camerawesome | Flutter package
- 定位 Search results for geolocator
- 使用 svg 图片 flutter_svg | Flutter package
- 简单本地存储 shared_preferences | Flutter package
- 选择图片上传 image_picker | Flutter package
- 唤起原生样式 webview flutter_custom_tabs | Flutter package
- 唤起第三方 APP url_launcher | Flutter package
- 低功耗蓝牙,支持中心设备 Central 和外围设备 Peripheral bluetooth_low_energy | Flutter package
- TensorFlow Lite 加载模型 tflite_flutter | Flutter package
- GraphQL 工具 graphql_flutter | Flutter package