Flutter可穿戴设备旋转输入插件wearable_rotary的使用

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

Flutter可穿戴设备旋转输入插件wearable_rotary的使用

wearable_rotary

pub package

wearable_rotary 是一个Flutter插件,可以监听Wear OS和Tizen Galaxy手表设备上的旋转事件。

Setup

Android

MainActivity.kt 中添加以下代码:

import android.view.MotionEvent
import com.samsung.wearable_rotary.WearableRotaryPlugin

class MainActivity : FlutterActivity() {
    override fun onGenericMotionEvent(event: MotionEvent?): Boolean {
        return when {
            WearableRotaryPlugin.onGenericMotionEvent(event) -> true
            else -> super.onGenericMotionEvent(event)
        }
    }
}

Usage

要在项目中使用此插件,在 pubspec.yaml 文件中添加 wearable_rotary 作为依赖项。

dependencies:
  wearable_rotary: ^2.0.1

然后在Dart代码中导入 wearable_rotary 包。

// Import the package.
import 'package:wearable_rotary/wearable_rotary.dart';

// Be informed when an event (RotaryEvent.clockwise or RotaryEvent.counterClockwise) occurs.
StreamSubscription<RotaryEvent> rotarySubscription =
    rotaryEvents.listen((RotaryEvent event) {
  if (event.direction == RotaryDirection.clockwise) {
    // Do something.
  } else if (event.direction == RotaryDirection.counterClockwise) {
    // Do something.
  }
});

// Be sure to cancel on dispose.
rotarySubscription.cancel();

// Use [RotaryScrollController] to easily make scrolling widgets respond to rotary input.
ListView(controller: RotaryScrollController());

Supported devices

  • Wear OS设备(如Galaxy Watch 4、Pixel Watch等)带有旋转输入功能。
  • 运行Tizen 5.5的Galaxy Watch系列。

示例代码

下面是一个完整的示例应用程序,演示了如何使用 wearable_rotary 插件来处理旋转事件,并将这些事件应用于水平或垂直滚动视图。

// Copyright 2021 Samsung Electronics Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

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

void main() {
  runApp(
    MaterialApp(
      title: 'Rotary example app',
      home: const MyApp(),
      // Set the target platform to iOS so that navigation behaves as expected for a wearable app
      theme: ThemeData(platform: TargetPlatform.iOS),
    ),
  );
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Rotary example app')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              child: const Text('HorizontalScrollView'),
              onPressed: () {
                Navigator.push<dynamic>(
                  context,
                  MaterialPageRoute<dynamic>(
                    builder: (BuildContext context) => const RotaryScrollPage(
                      scrollDirection: Axis.horizontal,
                    ),
                  ),
                );
              },
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              child: const Text('VerticalScrollView'),
              onPressed: () {
                Navigator.push<dynamic>(
                  context,
                  MaterialPageRoute<dynamic>(
                    builder: (BuildContext context) =>
                        const RotaryScrollPage(scrollDirection: Axis.vertical),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

class RotaryScrollPage extends StatelessWidget {
  const RotaryScrollPage({super.key, required this.scrollDirection});

  final Axis scrollDirection;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          scrollDirection == Axis.vertical
              ? 'VerticalScrollView'
              : 'HorizontalScrollView',
        ),
      ),
      body: Center(
        child: ListView.builder(
          padding: const EdgeInsets.all(16),
          controller: RotaryScrollController(),
          scrollDirection: scrollDirection,
          itemCount: 1000,
          itemBuilder: (BuildContext context, int index) => Text('Item $index'),
        ),
      ),
    );
  }
}

这个示例展示了如何创建一个包含两个按钮的应用程序,点击按钮后会导航到一个新的页面,该页面根据选择的方向(水平或垂直)显示一个可滚动的列表。通过使用 RotaryScrollController,列表能够响应旋转输入事件,提供更自然的用户体验。


更多关于Flutter可穿戴设备旋转输入插件wearable_rotary的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter可穿戴设备旋转输入插件wearable_rotary的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中集成和使用wearable_rotary插件来实现可穿戴设备旋转输入的示例代码。这个插件通常用于Tizen或Wear OS等可穿戴设备上,允许用户通过旋转表冠或类似输入设备来进行交互。

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

dependencies:
  flutter:
    sdk: flutter
  wearable_rotary: ^最新版本号  # 请替换为实际的最新版本号

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

接下来,你可以在你的Flutter应用中实现旋转输入监听。以下是一个简单的示例代码:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Wearable Rotary Input Example'),
        ),
        body: Center(
          child: RotaryInputExample(),
        ),
      ),
    );
  }
}

class RotaryInputExample extends StatefulWidget {
  @override
  _RotaryInputExampleState createState() => _RotaryInputExampleState();
}

class _RotaryInputExampleState extends State<RotaryInputExample> with SingleTickerProviderStateMixin {
  double _value = 0.0;

  @override
  void initState() {
    super.initState();
    // 初始化RotaryController
    RotaryController.instance.addListener(() {
      setState(() {
        _value += RotaryController.instance.delta;
        // 限制值在0到360之间循环
        if (_value >= 360) _value -= 360;
        if (_value < 0) _value += 360;
      });
    });
  }

  @override
  void dispose() {
    // 移除监听器
    RotaryController.instance.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(
          'Rotated Value: $_value°',
          style: TextStyle(fontSize: 24),
        ),
        SizedBox(height: 20),
        CircularProgressIndicator(
          value: _value / 360,
          semanticsLabel: 'Rotated progress',
        ),
      ],
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个文本显示旋转的角度值和一个圆形进度条来可视化旋转的进度。

  • RotaryController.instance.addListener用于监听旋转事件。每当用户旋转输入设备时,RotaryController.instance.delta会包含旋转的增量值。
  • _value变量用于存储当前的旋转角度,并限制其在0到360度之间循环。
  • CircularProgressIndicator用于显示旋转进度的可视化表示。

请注意,wearable_rotary插件的实际使用可能会因设备和操作系统的不同而有所差异。确保在目标设备上测试你的应用,并根据需要进行调整。此外,这个插件可能需要特定的权限或配置才能在目标设备上正常工作,请查阅官方文档以获取更多信息。

回到顶部