Flutter常量管理插件flutter_const的使用
Flutter常量管理插件flutter_const的使用
关键点 :
- 该插件允许开发者以最简单的方式从服务器获取数据。
- FcNavigator 导航器使导航过程更加简便。
- 移除列表视图的闪烁效果(Glow Behavior)。
- 提前构建响应式文本样式。
- 水平和垂直方向上的尺寸替代 SizedBox。
- 双击退出功能。
- 暗黑模式支持。
如何使用
要使用 flutter_const
插件,首先需要导入包:
import 'package:flutter_const/flutter_const.dart';
列表视图无闪烁效果 (ListView No Glow)
通过设置 ScrollConfiguration
来移除列表视图的闪烁效果:
class Demo extends StatelessWidget {
const Demo({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Container(
child: ScrollConfiguration(
behavior: FcNoGlowBehavior(), // 移除列表视图的滚动闪烁效果
child: Container(),
),
);
}
}
双击退出功能 (Backpress)
通过 WillPopScope
实现双击退出功能:
class Demo extends StatelessWidget {
const Demo({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return Container(
child: WillPopScope(
onWillPop: fcOnWillPop, // 双击退出逻辑
child: ListView(),
),
);
}
}
API 调用
使用 ApiHelper
类来调用 API:
Future<Album> fetchAlbum() async {
ApiHelper _helper = ApiHelper();
final response = await _helper.get(baseurl: 'jsonplaceholder.typicode.com', url: 'albums/2');
return Album.fromJson(response);
}
暗黑模式 (Dark Mode)
在 MaterialApp
中设置亮暗主题:
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: FcTheme.light, // 亮色主题
darkTheme: FcTheme.dark, // 暗色主题
themeMode: ThemeMode.system, // 系统默认模式
home: MyHomePage(),
);
}
}
文本样式 (Text Style)
使用 FcTextStyle
定义统一的文本样式:
FcTextStyle textStyle = FcTextStyle();
ElevatedButton(
onPressed: () {},
child: Text(
'move to second page',
style: textStyle.buttonText(context), // 使用预定义的按钮文本样式
),
)
文本格式化 (Text Format)
支持字符串的首字母大写格式化:
Text(
"data join".capitalizeFirstOfEach, // 首字母大写格式化
style: textStyle.h6Text(context),
)
尺寸管理 (Dimensions)
使用 fcVSizedBox
和 fcHSizedBox
来管理水平和垂直间距:
// 垂直方向
fcVSizedBox // 5px
fcVSizedBox1 // 10px
fcVSizedBox2 // 20px
fcVSizedBox3 // 40px
fcVSizedBox4 // 80px
fcVSizedBox5 // 160px
fcVSizedBox6 // 320px
// 水平方向
fcHSizedBox // 5px
fcHSizedBox1 // 10px
fcHSizedBox2 // 20px
fcHSizedBox3 // 40px
fcHSizedBox4 // 80px
fcHSizedBox5 // 160px
fcHSizedBox6 // 320px
导航管理 (Navigations)
使用 FcNavigator
进行页面跳转:
FcNavigator().push(context, screen: SecondPage());
完整示例代码
以下是一个完整的示例代码,展示如何使用 flutter_const
插件的功能:
import 'package:flutter/material.dart';
import 'package:flutter_const/flutter_const.dart';
import 'package:flutter_const/server/api_helper.dart';
// 模型类
class Album {
final int userId;
final int id;
final String title;
Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
// 数据请求
Future<Album> fetchAlbum() async {
ApiHelper _helper = const ApiHelper();
final response = await _helper.get(url: 'https://jsonplaceholder.typicode.com/albums/2');
return Album.fromJson(response);
}
// 主应用
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: FcTheme.light,
darkTheme: FcTheme.dark,
themeMode: ThemeMode.dark,
home: const MyHomePage(),
);
}
}
// 第一页
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String? data;
[@override](/user/override)
Widget build(BuildContext context) {
FcTextStyle textStyle = const FcTextStyle();
return Scaffold(
appBar: AppBar(
title: Text(
"First Screen",
style: textStyle.h6BText(context),
),
),
body: Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
FcNavigator().push(context, screen: const SecondPage());
},
child: const Text('move to second page'),
),
fcVSizedBox2, // 垂直间距 20px
Text(
"data join".capitalizeFirstOfEach,
style: textStyle.h6Text(context),
),
fcVSizedBox2,
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
decoration: BoxDecoration(
color: Theme.of(context).primaryColorLight,
borderRadius: const BorderRadius.all(Radius.circular(20)),
),
child: TextField(
decoration: const InputDecoration(border: InputBorder.none, hintText: "Password"),
style: textStyle.subtitleText(context),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
],
),
);
}
}
// 第二页
class SecondPage extends StatefulWidget {
const SecondPage({Key? key}) : super(key: key);
[@override](/user/override)
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
late Future<Album> futureAlbum;
[@override](/user/override)
void initState() {
futureAlbum = fetchAlbum();
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
FcTextStyle textStyle = const FcTextStyle();
return Scaffold(
appBar: AppBar(
title: const Text("Second Screen"),
),
body: SizedBox(
width: double.infinity,
child: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
snapshot.data!.title,
style: textStyle.bodyBText(context),
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return const CircularProgressIndicator(); // 加载中
},
),
),
),
);
}
}
更多关于Flutter常量管理插件flutter_const的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter常量管理插件flutter_const的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,管理常量是一个常见的需求,尤其是在大型项目中,常量可能会分散在多个文件中,导致维护困难。为了更有效地管理常量,可以使用 flutter_const
插件。这个插件可以帮助你集中管理常量,并且通过代码生成的方式自动生成常量类。
1. 安装 flutter_const
插件
首先,你需要在 pubspec.yaml
文件中添加 flutter_const
插件的依赖:
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_const: ^1.0.0
然后运行 flutter pub get
来安装依赖。
2. 创建常量配置文件
接下来,你需要在项目中创建一个常量配置文件。通常,这个文件可以命名为 constants.yaml
或 consts.yaml
,并放在项目的根目录下。
# constants.yaml
app_name: "My Flutter App"
api_url: "https://api.example.com"
theme:
primary_color: "#6200EE"
accent_color: "#03DAC6"
3. 生成常量类
在 constants.yaml
文件创建好后,你可以通过运行以下命令来生成常量类:
flutter pub run flutter_const
这个命令会根据 constants.yaml
文件生成一个 Dart 文件,通常命名为 constants.dart
,并将其放在 lib
目录下。
4. 使用生成的常量类
生成的 constants.dart
文件会包含一个 Constants
类,你可以通过这个类来访问你在 constants.yaml
中定义的常量。
import 'package:my_app/constants.dart';
void main() {
print(Constants.appName); // 输出: My Flutter App
print(Constants.apiUrl); // 输出: https://api.example.com
print(Constants.theme.primaryColor); // 输出: #6200EE
}
5. 更新常量
如果你需要更新常量,只需修改 constants.yaml
文件,然后重新运行 flutter pub run flutter_const
命令即可。生成的 constants.dart
文件会自动更新。
6. 自定义生成路径和文件名
你可以通过修改 flutter_const
的配置来自定义生成路径和文件名。在 pubspec.yaml
中添加以下配置:
flutter_const:
output: lib/generated/constants.dart
input: assets/constants.yaml