Flutter屏幕适配与布局调整插件flutter_fit_utils的使用
Flutter屏幕适配与布局调整插件flutter_fit_utils的使用
Flutter屏幕适配与布局调整插件flutter_fit_utils的使用
标题:Flutter屏幕适配与布局调整插件flutter_fit_utils的使用
内容如下:
A flutter package to easily manage data in and out of repositories. This package is the core of it’s environement. To know about other packages related to flutter_fit_utils, see the diagram below.
Features
Use this package to: - Get a uniform way of reading and writing data with Models. - Create a repository and a service for your data with a single line of code. - Get access to extensions for multiple flutter base classes.Here are the supported repositories:
- Firebase Firestore
- Hive
- Firebase Remote Config (Read Only)
- shared_preferences
- Firebase Storage (soon)
Getting started
- Go inside your pubspec.yaml file
- Add this line under the dependencies:
flutter_fit_utils: ^2.0.0
- Get dependencies
flutter pub get
Usage
Creating a model
Make a class Modelable so it can be managed by a service and sent to a repository. For example:
import 'package:flutter_fit_utils/flutter_fit_utils.dart';/// Example user class. class User extends Modelable { static const String _nameKey = “name”;
/// User’s last name. final String name;
/// Creates a new user. const User({this.name = “”, super.id, super.userId});
/// Creates an invalid user. const User.invalid() : name = “”, super.invalid();
/// Creates a user from a [Model]. User.fromModel(super.model) : name = model.data[_nameKey].toString(), super.fromModel();
@override User copyWith({String? id, String? userId, bool? invalid, String? name}) => User( name: name ?? this.name, id: id ?? this.id, userId: userId ?? this.userId, );
@override Model toModel() => Model( id: id, userId: userId, data: { _nameKey: name, }, ); }
If creatinging an entire class is too much for your use case, this package offers extensions to convert primitive types to Models:
final int myValue = 1;
final Model model = myValue.toModel();
final int otherValue = intFromModel(model);
Here are the supported types:
- int
- double
- num
- bool
- String
- List (Of Modelable objects)
- Map<String, dynamic>
Managing your model with a service
You can create a service for your model with a single line of code:
```dart import 'package:flutter_fit_utils/flutter_fit_utils.dart';final Service<User> userService = FirestoreService(“my_user_collection”, User.fromModel);
In the case of FirestoreCollection, the only thing you have to do is go to your Firebase project, and create a new collection "my_user_collection" in your database.
If you want more control over your service, you can also create a custom one:
```dart
import 'package:flutter_fit_utils/flutter_fit_utils.dart';
final class CustomUserService extends Service<User> {
CustomUserService(super.repositoryId, super.fromModelFactory) {
repository = FirestoreCollection(collectionId: repositoryId);
}
[@override](/user/override)
Future<List<UserData>> getAll({String? userId, Where? where, String? orderBy, bool descending = true}) async {
// Implement your custom logic...
}
}
Note that you can override any function of the base Service class.
Additional information
Feel free to give any feedback ! This package is also openn to contributionsions. ``` ```示例代码如下:
import 'package:example/user.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fit_utils/flutter_fit_utils.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
final Service<User> userService = HiveService("users", User.fromModel);
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
Hive.init((await getApplicationDocumentsDirectory()).path);
await userService.repository.initialize();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MaterialButton(
onPressed: () async {
User newUser = User(name: (await userService.count()).toString());
var id = await userService.create(newUser);
newUser = newUser.copyWith(id: id, userId: id);
await userService.update(newUser);
},
child: const Text("Add User"),
),
MaterialButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => Scaffold(
appBar: AppBar(),
body: Container(
margin: const EdgeInsets.all(12),
child: FutureBuilder(
future: userService.getAll(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView(
children: [
Text("(${snapshot.requireData.length})"),
for (final user in snapshot.requireData)
ExpansionTile(
title: Text(user.name),
children: [
Text("ID: ${user.id}"),
Text("User ID: ${user.userId}"),
],
),
],
);
}
return const CircularProgressIndicator();
},
),
),
)));
},
child: const Text("View Users"),
),
],
),
),
);
}
}
更多关于Flutter屏幕适配与布局调整插件flutter_fit_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter屏幕适配与布局调整插件flutter_fit_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter开发中,屏幕适配与布局调整是一个常见且重要的需求。flutter_fit_utils
是一个可以帮助你实现这一目标的插件。下面是一个如何使用 flutter_fit_utils
的代码示例,包括如何在你的 Flutter 项目中集成和使用它来进行屏幕适配和布局调整。
1. 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 flutter_fit_utils
的依赖:
dependencies:
flutter:
sdk: flutter
flutter_fit_utils: ^最新版本号 # 请替换为实际发布的最新版本号
然后运行 flutter pub get
来获取依赖。
2. 初始化插件
在你的主应用入口文件(通常是 main.dart
)中,初始化 flutter_fit_utils
。这通常是在 MaterialApp
或 CupertinoApp
的构建函数中完成的。
import 'package:flutter/material.dart';
import 'package:flutter_fit_utils/flutter_fit_utils.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 初始化屏幕适配配置
ScreenFitUtils.init(context);
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
3. 使用适配后的尺寸
flutter_fit_utils
提供了多种方法来帮助你进行屏幕适配。以下是一些常见的使用场景:
a. 适配屏幕尺寸
你可以使用 ScreenFitUtils.screenWidth
和 ScreenFitUtils.screenHeight
来获取适配后的屏幕尺寸。
import 'package:flutter/material.dart';
import 'package:flutter_fit_utils/flutter_fit_utils.dart';
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('屏幕适配示例'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'屏幕宽度: ${ScreenFitUtils.screenWidth.toInt()} px',
style: TextStyle(fontSize: ScreenFitUtils.sp(16)), // 使用适配后的字体大小
),
Text(
'屏幕高度: ${ScreenFitUtils.screenHeight.toInt()} px',
style: TextStyle(fontSize: ScreenFitUtils.sp(16)),
),
],
),
),
);
}
}
b. 适配字体大小
你可以使用 ScreenFitUtils.sp(float size)
方法来根据屏幕尺寸动态计算字体大小。
Text(
'适配后的字体',
style: TextStyle(fontSize: ScreenFitUtils.sp(18)), // 18sp 转换为 px
)
c. 适配图片大小
你可以使用 ScreenFitUtils.scaleWidth(float size)
和 ScreenFitUtils.scaleHeight(float size)
方法来根据屏幕尺寸动态计算图片或其他视图元素的尺寸。
Image.asset(
'assets/images/example.png',
width: ScreenFitUtils.scaleWidth(100), // 100dp 转换为 px
height: ScreenFitUtils.scaleHeight(100), // 100dp 转换为 px
)
总结
通过以上步骤,你可以在 Flutter 项目中集成并使用 flutter_fit_utils
插件来实现屏幕适配和布局调整。这个插件提供了一系列实用的方法来帮助你处理不同屏幕尺寸和分辨率下的布局问题,使得你的应用能够在各种设备上都有良好的显示效果。