在Flutter中,各開發人員提供了對共享軟件包的支持,這使我們能夠輕松構建應用程序。它可以避免開發人員從頭開始開發。我們可能使用它們來請求網絡(HTTP),API集成以及使用第三方平臺。在本文中,我會列出21個Flutter軟件包以簡化Flutter的開發,一起來看一下(這些都在以下網站列出):
https://pub.dev/
Path_provider
這是一個用于在IOS和Android開發環境中的文件系統上定位文件的Flutter插件包
代碼示例:
Directory tempDir = await getTemporaryDirectory(); String tempPath = tempDir.path; Directory AppDocDir = await getApplicationDocumentsDirectory(); String appDocPath = appDocDir.path;
Url_launcher
這是一個Flutter插件,用于在移動平臺中啟動URL。它主要支持iOS和Android開發平臺。要使用url_launcher,請在pubspec.yaml文件中添加為依賴項。
代碼示例:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(Scaffold(
body: Center(
child: RaisedButton(
onPressed: _launchURL,
child: Text('...'),
),
),
));
}
_launchURL() async {
const url = '...';
if (await canLaunch(url)) {
await launch(url);
} else {
throw '...';
}
}
Image_picker
Image_picker是一用于在iOS和Android庫中選擇圖像,用戶也可以拍攝新圖像的flutter插件
代碼示例:
import 'package:image_picker/image_picker.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
File _image;
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker Example'),
),
body: Center(
child: _image == null
? Text('No image selected.')
: Image.file(_image),
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}
sqflite
SQLite插件,支持iOS和Android開發平臺
import ‘package: sqflite/sqflite.dart;
// 使用getDatabasePath獲取路徑
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
// 刪除數據庫
await deleteDatabase(path);
// 打開數據庫
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
// 創建數據庫時,也要創建表
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
cached_network_image
這是一個用于顯示緩存目錄中保存的來自互聯網的圖像的Flutter插件
代碼示例:
CachedNetworkImage( imageUrl: "http://via.placeholder.com/350x150", placeholder: (context, url) => new CircularProgressIndicator(), errorWidget: (context, url, error) => new Icon(Icons.error), ), Image(image: new CachedNetworkImageProvider(url))
google_maps_flutter
用于在iOS和Android應用程序上集成Google地圖。對于Android或iOS,請在應用清單中指定API密鑰,如下所示:
android/app/src/main/AndroidManifest.xml: -- ios/Runner/AppDelegate.m:
代碼示例:
ios/Runner/AppDelegate.m:
#include "AppDelegate.h"
#include "GeneratedPlug-inRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:@"YOUR KEY HERE"];
[GeneratedPlug-inRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
Scope model
這些是用于將數據模型從父窗口小部件傳遞到其后代的實用程序集。更新模型時,它將重建自己的子代
/**
創建一個擁有一些視圖狀態的類計數器從0開始,可以遞增。注意:它必須從Model擴展。
*/
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
// 首先,增加計數器
_counter++;
// 然后通知所有偵聽器。
notifyListeners();
}
}
class CounterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new ScopedModel<CounterModel>(
model: new CounterModel(),
child: new Column(children: [
new ScopedModelDescendant<CounterModel>(
builder: (context, child, model) => new Text('${model.counter}'),
),
new Text("Another widget that doesn't depend on the CounterModel")
])
);
}
}
Provider
這是一個為小部件構建的依賴項注入系統。
代碼示例:
- 公開一個值:
小部件包裝到包中的提供程序小部件中,然后將其傳遞給變量,以便所有新的提供程序都可以訪問變量
Provider<String>.value( value: 'Hello World!', child: MaterialApp( home: Home(), ) )
- 讀取一個值
Provider<String>.value( value: 'Hello World', child: Consumer<String>( builder: (context, value, child) => Text(value), ), );
- 多個Provider
Provider<Foo>.value( value: foo, child: Provider<Bar>.value( value: bar, child: Provider<Baz>.value( value: baz, child: someWidget, ) ) )
firebase_storage
這是用于Firebase云存儲API的flutter插件,它是功能強大,簡單且經濟高效的對象存儲服務,適用于Android和iOS。要使用此插件,pubspec.yaml文件中將添加firebase_ storgage為依賴項,此插件仍在開發中,某些API可能尚不可用。
Flutter_webview_plug-in
這是一個允許flutter與本機Webview進行通信flutter插件。下面是一個使用flutter導航啟動全屏Webview的示例。當頁面加載時,hidden和initialChild可用于顯示其他內容。
new MaterialApp(
routes: {
"/": (_) => new WebviewScaffold(
url: "https://...",
appBar: new AppBar(
title: new Text("Widget webview"),
),
),
},
);
Package_info
這是一個提供用于在Android和iOS上查詢應用程序包信息的API的插件
Import 'package: package_info/package_info.dart'; PackageInfo packageInfo = await PackageInfo.fromPlatform(); String appName = packageInfo.appName; String packageName = packageInfo.packageName; String version = packageInfo.version; String buildNumber = packageInfo.buildNumber;
device_info
用于提供有關設備的詳細信息,例如品牌,型號以及Android或iOS版本的插件。它提供有關手頭設備的當前信息。
Import 'package:device_info/device_info.dart';
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print('Running on ${androidInfo.model}');
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
print('Running on ${iosInfo.utsname.machine}');
bloCbuilder
一個Flutter小部件,它簡化了業務邏輯組件設計模式的實現。這是一個需要Bloc和Builder功能的Flutter小部件。BlocBuilder負責根據新狀態下的響應來構建窗口小部件。BlockBuilder與streamBuilder相似,但由于其簡單的API,因此所需的代碼量更少。例:
BlocBuilder(
bloc: BlocA(),
builder: (context, state) {
//根據BlocA的狀態返回小部件
}
)
webview_flutter
可在iOS和Android上提供Webview小部件。WKWwebview在iOS上支持webview,而webView在Android上支持webview
Location
可處理iOS Android上的實時位置。它還提供性能和電池優化設置。
import 'package:location/location.dart';
var currentLocation = LocationData;
var location = new Location();
try {
currentLocation = await location.getLocation();
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'Permission denied';
}
currentLocation = null;
}
var location = new Location();
location.onLocationChanged().listen((LocationData currentLocation) {
print(currentLocation.latitude);
print(currentLocation.longitude);
});
Flutter Spinkit
它是一組loading加載器,這些loading隨著抖動而動起來,以便在加載過程繼續進行時為用戶提供漂亮的外觀。
SpinKitFadingCircle(
itemBuilder: (_, int index) {
return DecoratedBox(
decoration: BoxDecoration(
color: index.isEven ? Colors.red : Colors.green,
),
);
},
);
AudioPlayers
用于在Android和iOS中同時播放多個音頻文件。
audioplayers: ^0.13.0 AudioPlayer audioPlayer = AudioPlayer (); AudioPlayer audioPlayer = AudioPlayer (mode: playermode.LOW_LATENCY);
Image_cropper
它是適用于iOS和Android的Flutter插件,支持裁剪圖片。
Connectivity
允許Flutter應用發現網絡連接并進行相應配置。該插件具有區分蜂窩連接和WiFi連接的能力。
import 'package:connectivity/connectivity.dart';
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
//我已連接到移動網絡
} else if (connectivityResult == ConnectivityResult.wifi) {
//我已連接到WIFI
}
Shimmer
提供了一種在flutter項目中添加閃爍效果的簡便方法。
SizedBox( width: 200.0, height: 100.0, child: Shimmer.fromColors( baseColor: Colors.red, highlightColor: Colors.yellow, child: Text( 'Shimmer', textAlign: TextAlign.center, style: TextStyle( fontSize: 40.0, fontWeight: FontWeight.bold, ), ), ), );
Share Plug-in
用于通過共享對話框共享來自flutter應用程序的內容。它包裝了Android上的ACTION_SEND intent和iOS上的UIActivityViewController。
import 'package:share/share.dart'; Share.share(check out my website https://....com');
總結
Flutter軟件包使我們能夠快速構建應用程序,并節省寶貴的時間來構建產品,大大提升了工作效率。






