Flutter多功能工具箱插件flutter_toolbox的使用

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

Flutter多功能工具箱插件flutter_toolbox的使用

flutter_toolbox 是一个包含通用 Flutter 小部件和辅助方法的库。它旨在简化开发过程中的一些常见任务。

开始使用

要开始使用 flutter_toolbox,首先需要将其添加到你的 pubspec.yaml 文件中:

dependencies:
  flutter_toolbox: ^x.y.z

其中 x.y.z 是你需要安装的具体版本号。接着运行 flutter pub get 来安装该依赖。

完整示例

以下是一个完整的示例,展示了如何在应用中使用 flutter_toolbox 的部分功能。

主文件 (main.dart)
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_toolbox/flutter_toolbox.dart';
import 'package:flutter_toolbox/generated/l10n.dart' as toolbox;
import 'package:flutter_toolbox_example/auth_navigation.dart';
import 'package:provider/provider.dart';

import 'auth_provider.dart';
import 'paginated_list_view_example.dart';

void main() => runApp(const MyApp());

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

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

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => AuthProvider()),
      ],
      child: Consumer<AuthProvider>(
        builder: (context, value, child) {
          return ToolboxApp(
            toolboxConfig: ToolboxConfig(
              useWeservResizer: true,
              noItemsFoundWidget: const Icon(Icons.subject),
              unAuthenticatedPages: const [
                LoginPage,
                AuthNavHomePage,
                NoAuthPage,
                PaginatedListViewPage,
                PaginatedListViewExample,
                PaginatedListViewEmptyExample,
                PagewiseSliverListExample,
              ],
              isAuthenticated: () {
                final isLoggedIn = value.getUserCashed() != null;
                print("isLoggedIn = $isLoggedIn"); // 打印是否已登录

                return isLoggedIn;
              },
              onAuthorizedNavigation: (BuildContext context, Type pageType) {
                print("onAuthorizedNavigation#pageType = $pageType"); // 打印授权导航类型
                return Navigator.push(context, MaterialPageRoute(builder: (_) => const LoginPage()));
              },
            ),
            child: MaterialApp(
              localizationsDelegates: const [
                toolbox.S.delegate,
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
              ],
              supportedLocales: const [
                Locale("en", ""),
                Locale("ar", ""),
              ],
              theme: ThemeData(
                tabBarTheme: TabBarTheme(
                  indicator: TabRoundedLineIndicator(
                    context,
                    indicatorSize: TabRoundedLineIndicatorSize.normal,
                    indicatorHeight: 3,
                  ),
                ),
              ),
              home: const HomePage(),
            ),
          );
        },
      ),
    );
  }
}
主页面 (HomePage.dart)
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  [@override](/user/override)
  HomePageState createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  [@override](/user/override)
  void initState() {
    super.initState();

    ConnectionStatusBar.init(context); // 初始化连接状态栏
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    var themeData = Theme.of(context);

    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: const Text(
            '插件示例应用',
            style: TextStyle(color: Colors.black87),
          ),
          backgroundColor: Colors.white,
          bottom: TabBar(
            labelStyle: const TextStyle(fontWeight: FontWeight.w700),
            indicatorSize: TabBarIndicatorSize.label,
            labelColor: themeData.primaryColor,
            unselectedLabelColor: const Color(0xff5f6368),
            isScrollable: true,
            indicator: TabRoundedLineIndicator(
              context,
              indicatorSize: TabRoundedLineIndicatorSize.normal,
              indicatorHeight: 3,
              indicatorColor: Theme.of(context).primaryColor,
            ),
            tabs: const [
              Tab(text: "首页"),
              Tab(text: "个人信息"),
              Tab(text: "数据与个性化"),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const PaginatedListViewPage())),
              child: const Text('分页列表页面'),
            )
          ],
        ),
        body: Builder(builder: (context) {
          return Column(
            children: [
              Text(toolbox.S.of(context)?.please_check_your_connection ?? '请检查您的连接'),
              const NetImage(
                'https://via.placeholder.com/300',
                width: 300,
                fullScreen: true,
              ),
              const NetImage(
                'https://via.placeholder.com/50',
                fullScreen: true,
                width: 50,
              ),
              NetImage(
                'https://via.placeholder.com/50',
                width: 50,
                borderRadius: BorderRadius.circular(8),
              ),
              NetImage(
                "",
                width: 50,
                borderRadius: BorderRadius.circular(8),
              ),
              Row(
                children: [
                  MaterialButton(
                    child: const Text('错误提示'),
                    onPressed: () => errorToast('错误'),
                  ),
                  MaterialButton(
                    child: const Text('成功提示'),
                    onPressed: () => successToast('成功'),
                  ),
                  MaterialButton(
                    child: const Text('普通提示'),
                    onPressed: () => toast('欢迎回来'),
                  ),
                ],
              ),
              MaterialButton(
                child: const Text('授权导航'),
                onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const AuthNavHomePage())),
              ),
            ],
          );
        }),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用flutter_toolbox插件的示例代码。flutter_toolbox是一个提供多种常用功能的Flutter插件,比如设备信息获取、屏幕截图、文件操作等。为了简洁起见,这里只展示几个核心功能的用法。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_toolbox: ^最新版本号 # 请替换为当前最新版本号

然后运行flutter pub get来安装依赖。

接下来,在你的Dart文件中导入flutter_toolbox

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

示例代码

1. 获取设备信息

void _getDeviceInfo() async {
  DeviceInfo deviceInfo = await FlutterToolbox.deviceInfo;
  print('品牌: ${deviceInfo.brand}');
  print('型号: ${deviceInfo.model}');
  print('系统版本: ${deviceInfo.systemVersion}');
}

2. 屏幕截图

void _takeScreenshot() async {
  File screenshot = await FlutterToolbox.captureScreen();
  print('截图保存路径: ${screenshot.path}');
  // 可以选择将截图显示给用户或者保存到相册等
}

3. 文件操作(读取文件内容)

void _readFile() async {
  String filePath = 'path/to/your/file.txt'; // 请替换为实际文件路径
  String content = await FlutterToolbox.readFile(filePath);
  print('文件内容: $content');
}

4. 闪屏页倒计时

void _showSplashScreen() async {
  // 显示一个简单的闪屏页,并在3秒后导航到主页面
  await FlutterToolbox.showSplash(
    context,
    imagePath: 'assets/splash.png', // 请替换为你的闪屏图路径
    duration: Duration(seconds: 3),
    nextPage: MyHomePage(), // 导航到的目标页面
  );
}

5. 振动设备

void _vibrateDevice() async {
  await FlutterToolbox.vibrate(duration: 500); // 振动500毫秒
}

在UI中调用这些功能

你可以将这些功能绑定到按钮点击事件或其他用户交互事件中。例如:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Toolbox Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: _getDeviceInfo,
                child: Text('获取设备信息'),
              ),
              ElevatedButton(
                onPressed: _takeScreenshot,
                child: Text('屏幕截图'),
              ),
              ElevatedButton(
                onPressed: _readFile,
                child: Text('读取文件'),
              ),
              ElevatedButton(
                onPressed: () async {
                  await _showSplashScreen();
                },
                child: Text('显示闪屏页'),
              ),
              ElevatedButton(
                onPressed: _vibrateDevice,
                child: Text('振动设备'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

这个示例展示了如何在Flutter应用中集成和使用flutter_toolbox插件的一些核心功能。根据具体需求,你可以进一步探索和使用插件提供的更多功能。

回到顶部