Flutter功能扩展插件flutter_gearbox的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter功能扩展插件flutter_gearbox的使用

Flutter Package包含了一些常用的实用函数(如日志记录器、应用路由、SnackBar、网络工具、自定义扩展、UrlLauncher、自定义文本字段等),这些都发布在Pub dev上。

支持的设备

  • Android
  • iOS
  • Linux
  • Windows
  • macOS

安装

  1. 在你的pubspec.yaml文件中添加最新版本的包,并运行dart pub get
dependencies:
  flutter_gearbox: 
  1. 导入该包并在你的Flutter应用中使用它:
import 'package:flutter_gearbox/flutter_gearbox.dart';
  1. 在Material App中添加Keys以进行路由和无BuildContext显示SnackBar:
MaterialApp(
  scaffoldMessengerKey: snackbarKey,
  navigatorKey: navigatorKey,
  ...
)

功能

  • ✅ 自定义日志记录器
    • ✅ print
    • ✅ info
    • ✅ verbose
    • ✅ wtf
    • ✅ debug
    • ✅ warning
    • ✅ error
  • ✅ 自定义应用路由 无BuildContext
    • ✅ push
    • ✅ pushOFFAll
    • ✅ pushNamed
    • ✅ pop
  • ✅ 显示SnackBar 无BuildContext
    • ✅ showSnackBar
  • ✅ 空间
    • ✅ 垂直空间
    • ✅ 水平空间
  • ✅ 网络工具
    • ✅ isConnectionAvailable
    • ✅ performAction
    • ✅ listenConnectionStream
  • ✅ 自定义文本字段
    • ✅ NameTextField
    • ✅ SearchTextField
    • ✅ EmailTextField
    • ✅ PasswordTextField
    • ✅ PhoneNumberTextField
  • ✅ 状态码
    • ✅ statusOk
    • ✅ statusNotFound
    • ✅ statusInvalidRequest
    • ✅ statusInternalServerError
  • ✅ UrlLauncher
    • ✅ launchURL
  • ✅ 扩展
    • ✅ string_extension --> capitalize
  • ✅ 自定义变量
    • ✅ isInProduction
    • ✅ isDebugMode
  • ✅ 自定义屏幕
    • ✅ NoInterNetScreen

示例

日志记录器

logger.error("My Error Print");

应用路由(无BuildContext)

appRouter.push(HomeScreen());

显示SnackBar(无BuildContext)

showSnackBar(msg: "MOM ❤");

空间

垂直空间
VerticalSpace(height: 10);
水平空间
HorizontalSpace(width: 10);

网络工具

final connectionStatus = await networkUtils.isConnectionAvailable();
await networkUtils.performAction();
await networkUtils.listenConnectionStream();

自定义文本字段

CustomTextField(text: "Enter your name");

状态码

if(res.status == statusOk) {
  // ...
}

UrlLauncher

await launchURL("google.com");

字符串扩展

String name = username.toString().capitalize;

自定义调试变量

if(isInProduction){
  // ... 报告到崩溃分析
}

if(isDebugMode) {
  print("HELLO WORLD");
}

无互联网屏幕

NoInterNetScreen();

下一步目标

  • ✅ 添加实用函数(扩展、日志记录器、导航器、网络、自定义屏幕、SnackBar、空间、状态码、自定义文本字段、UrlLauncher)
  • ❌ 需要添加更多功能

贡献

如果你发现了一个错误或想要一个新功能,但不知道如何修复/实现,请填写一个issue。
如果你修复了错误或实现了功能,请发送一个pull请求。


以下是完整的示例代码:

import 'package:example/home_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gearbox/flutter_gearbox.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  void initState() {
    super.initState();
    _init();
  }

  _init() async {
    /// [networkUtils.listenConnectionStream(Widget page) - listenToStream and perform push and pop based on the connectionStatus]
    await networkUtils.listenConnectionStream();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter GearBox Example',
      scaffoldMessengerKey: snackbarKey,
      navigatorKey: navigatorKey,
      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> {
  int _counter = 0;
  final controller = TextEditingController();

  void _incrementCounter() {
    setState(() {
      _counter++;
    });

    /// [isDebugMode] && [logger.error(value)]
    if (isDebugMode) logger.error(_counter);

    /// [showSnackBar] without BuildContext with pure Flutter & Dart Code.
    showSnackBar(msg: "MOM 💕💕");
  }

  Future<void> launchUrl() async {
    /// [launchURL - launch url from flutter app]
    await urlLauncher.launchURL("https://github.com/swarajkumarsingh");
  }

  void pushToHomeScreen() {
    /// [appRouter.push(Widget page) - push to screen without BuiltContext]
    appRouter.push(
      HomeScreen(
        /// [capitalize - function to capitalize the first letter]
        text: "${controller.text.capitalize} Happy Coding",
      ),
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            onPressed: pushToHomeScreen,
            icon: const Icon(Icons.home),
          ),
          IconButton(
              onPressed: () async => await launchUrl(),
              icon: const Icon(Icons.person))
        ],
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),

            /// [VerticalSpace - Create vertical height]
            const VerticalSpace(height: 10),

            /// [NameTextField - with pre-defined properties]
            NameTextField(text: "Enter your name", controller: controller),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter功能扩展插件flutter_gearbox的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter功能扩展插件flutter_gearbox的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,flutter_gearbox 是一个强大的 Flutter 插件,用于扩展 Flutter 应用的功能。虽然我不能提供具体的建议,但我可以展示如何使用 flutter_gearbox 的一些基础代码案例来帮助你理解其应用。

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_gearbox 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_gearbox: ^最新版本号

然后运行 flutter pub get 来获取依赖。

案例 1: 使用 flutter_gearbox 的主题管理功能

flutter_gearbox 提供了方便的主题管理功能。以下是一个简单的例子,展示如何使用它来切换主题。

  1. 初始化主题数据

在你的 main.dart 文件中:

import 'package:flutter/material.dart';
import 'package:flutter_gearbox/flutter_gearbox.dart';

void main() {
  // 初始化 Gearbox
  Gearbox.init(
    context: GearboxContext.app(),
    defaultSettings: GearboxSettings(
      themeMode: ThemeMode.system, // 或 ThemeMode.light / ThemeMode.dark
    ),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GearboxProvider(
      child: MaterialApp(
        title: 'Flutter Gearbox Demo',
        theme: Gearbox.of(context).themeData,
        darkTheme: Gearbox.of(context).darkThemeData,
        themeMode: Gearbox.of(context).themeMode,
        home: HomeScreen(),
      ),
    );
  }
}
  1. 创建一个切换主题的按钮

在你的 home_screen.dart 文件中:

import 'package:flutter/material.dart';
import 'package:flutter_gearbox/flutter_gearbox.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Gearbox Theme Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Theme Mode: ${Gearbox.of(context).themeMode.toString()}',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Gearbox.of(context).setThemeMode(
                  Gearbox.of(context).themeMode == ThemeMode.light
                      ? ThemeMode.dark
                      : ThemeMode.light,
                );
              },
              child: Text('Switch Theme'),
            ),
          ],
        ),
      ),
    );
  }
}

案例 2: 使用 flutter_gearbox 的本地化功能

flutter_gearbox 也支持本地化管理。以下是一个简单的例子,展示如何设置和使用本地化。

  1. 添加本地化资源

lib/locales 文件夹下创建 messages_en.dartmessages_zh.dart 文件,分别包含英文和中文的翻译。

// messages_en.dart
Map<String, String> en() {
  return {
    'welcome': 'Welcome',
  };
}

// messages_zh.dart
Map<String, String> zh() {
  return {
    'welcome': '欢迎',
  };
}
  1. 初始化本地化

main.dart 文件中初始化本地化:

import 'package:flutter/material.dart';
import 'package:flutter_gearbox/flutter_gearbox.dart';
import 'locales/messages_en.dart' as en;
import 'locales/messages_zh.dart' as zh;

void main() {
  // 初始化 Gearbox
  Gearbox.init(
    context: GearboxContext.app(),
    defaultSettings: GearboxSettings(
      locale: Locale('en'), // 默认语言
    ),
    localizations: [
      GearboxLocalization(
        'en',
        en.en,
      ),
      GearboxLocalization(
        'zh',
        zh.zh,
      ),
    ],
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GearboxProvider(
      child: MaterialApp(
        title: 'Flutter Gearbox Localization Demo',
        localizationsDelegates: [
          GearboxLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        supportedLocales: Gearbox.of(context).supportedLocales,
        locale: Gearbox.of(context).locale,
        home: HomeScreen(),
      ),
    );
  }
}
  1. 使用本地化文本

home_screen.dart 文件中使用本地化文本:

import 'package:flutter/material.dart';
import 'package:flutter_gearbox/flutter_gearbox.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Gearbox Localization Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              GearboxLocalizations.of(context)!.translate('welcome'),
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Gearbox.of(context).setLocale(
                  Gearbox.of(context).locale.languageCode == 'en'
                      ? Locale('zh')
                      : Locale('en'),
                );
              },
              child: Text('Switch Language'),
            ),
          ],
        ),
      ),
    );
  }
}

以上代码展示了如何使用 flutter_gearbox 进行主题管理和本地化设置。你可以根据需要进一步扩展这些功能。

回到顶部