Flutter模拟时钟选择器插件better_analog_time_picker的使用

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

Flutter模拟时钟选择器插件better_analog_time_picker的使用

Pub.dev

一个高度可定制的模拟时钟选择器插件,允许用户通过直观的界面轻松选择时间。此插件支持AM/PM选择、限制时间范围,并提供优雅的时钟UI。

示例预览

模拟时钟选择器预览

功能

  • 可定制初始时间:在打开选择器时设置初始时间。
  • 时间范围限制:防止用户选择指定范围之外的时间(例如过去的时间)。
  • AM/PM 支持:轻松切换AM和PM格式。
  • 直观的UI:一个视觉上吸引人的模拟时钟界面用于时间选择。
  • 用户交互:用户可以通过拖动时钟的手或点击小时/分钟标记来选择时间。

安装

要在您的Flutter项目中使用模拟时钟选择器插件,请将其添加到pubspec.yaml文件中:

dependencies:
  better_analog_time_picker: ^0.0.2

使用方法

要显示模拟时钟选择器,请使用以下代码片段:

final currentTime = TimeOfDay.now();
final minTime = TimeOfDay(hour: currentTime.hour, minute: currentTime.minute + 10); // 示例最小时间

final time = await AnalogTimePickerDialog.show(
  context,
  initialTime: currentTime,
  minTime: minTime,
  // maxTime: TimeOfDay(hour: currentTime.hour + 2, minute: currentTime.minute + 10), // 可选最大时间
);

参数

  • initialTime: 打开选择器时显示的初始时间。
  • minTime: 允许的最小时间(例如,防止选择过去的时间)。
  • maxTime: 允许的最大时间(可选)。

示例用法

ElevatedButton(
  onPressed: () async {
    final selectedTime = await AnalogTimePickerDialog.show(
      context,
      initialTime: currentTime,
      minTime: minTime,
      // maxTime: TimeOfDay(hour: currentTime.hour + 2, minute: currentTime.minute + 10),
    );

    if (selectedTime != null) {
      // 处理所选时间
      print("Selected Time: ${selectedTime.format(context)}");
    }
  },
  child: const Text("选择时间"),
)

自定义

您可以自定义时钟的外观,通过修改插件中的ClockPainter类。调整颜色、大小和样式以适应您的应用程序设计。

贡献

欢迎贡献!如果您有建议或改进,请创建一个拉取请求或打开一个问题。

许可证

该项目采用MIT许可证。详情请参阅LICENSE文件。


完整示例代码

import 'package:analog_time_picker/better_analog_time_picker.dart';
import 'package:flutter/material.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: '时间选择器演示',
      home: const HomeScreen(),
    );
  }
}

/// 主页面
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  [@override](/user/override)
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  static final _now = TimeOfDay.now();
  TimeOfDay _selectedTime = _now;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('时间选择器演示'),
      ),

      // 页面主体
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '所选时间:',
              style: const TextStyle(fontSize: 16),
            ),

            // 所选时间
            Text(
              _selectedTime.format(context),
              style: const TextStyle(fontSize: 24),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),

      // 悬浮按钮
      floatingActionButton: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          /// Material 时间选择器悬浮按钮
          FloatingActionButton.extended(
            onPressed: () {
              showTimePicker(
                context: context,
                initialTime: _now,
              ).then((TimeOfDay? time) {
                if (time != null) {
                  setState(() {
                    _selectedTime = time;
                  });
                }
              });
            },
            icon: const Icon(Icons.access_time),
            label: Text('打开Material选择器'),
          ),
          SizedBox(height: 32),

          /// 更好的时间选择器悬浮按钮
          FloatingActionButton.extended(
            onPressed: () async {
              final time = await AnalogTimePickerDialog.show(
                context,
                initialTime: _now,
                minTime: TimeOfDay(hour: _now.hour, minute: _now.minute + 10),
                // maxTime:
                //     TimeOfDay(hour: _now.hour + 2, minute: _now.minute + 10),
              );
              if (time != null) {
                setState(() {
                  _selectedTime = time;
                });
              }
            },
            icon: const Icon(Icons.access_time),
            label: Text('打开更好的时间选择器'),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter模拟时钟选择器插件better_analog_time_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter模拟时钟选择器插件better_analog_time_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用better_analog_time_picker插件的示例代码。这个插件允许你在应用中集成一个模拟时钟选择器,让用户能够选择时间。

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

dependencies:
  flutter:
    sdk: flutter
  better_analog_time_picker: ^x.y.z  # 请将x.y.z替换为最新版本号

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

接下来,在你的Flutter项目中,你可以使用以下代码来集成和使用better_analog_time_picker

示例代码

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Analog Time Picker Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  DateTime _selectedTime = DateTime.now();

  void _selectTime(BuildContext context) async {
    final DateTime? newTime = await showAnalogTimePicker(
      context: context,
      initialTime: _selectedTime,
      locale: Localizations.localeOf(context),
      theme: AnalogTimePickerTheme.light(),  // 或者使用 AnalogTimePickerTheme.dark()
      hourHandColor: Colors.blue,
      minuteHandColor: Colors.green,
      secondHandColor: Colors.red,
      clockFaceBackgroundColor: Colors.white,
      clockFaceBorderColor: Colors.black,
      numbersColor: Colors.black,
      numbersFontSize: 24.0,
      is24HourFormat: false,  // 设置为 true 以使用24小时格式
    );

    if (newTime != null && newTime != _selectedTime) {
      setState(() {
        _selectedTime = newTime;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Analog Time Picker Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Selected Time: ${_selectedTime.toLocal()}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _selectTime(context),
              child: Text('Select Time'),
            ),
          ],
        ),
      ),
    );
  }
}

代码解释

  1. 依赖添加:在pubspec.yaml中添加better_analog_time_picker依赖。
  2. 导入包:在Dart文件中导入better_analog_time_picker包。
  3. 创建应用:创建一个简单的Flutter应用,包含一个主页面。
  4. 状态管理:使用_MyHomePageState来管理选中时间的状态。
  5. 显示时钟选择器:使用showAnalogTimePicker函数来显示模拟时钟选择器,并处理选中时间的变化。
  6. 更新UI:在选中时间变化时,使用setState来更新UI。

这个示例展示了如何集成better_analog_time_picker并让用户选择时间。你可以根据需要进一步自定义时钟选择器的外观和行为。

回到顶部