Flutter 实现通过遥控器操作与部件进行交互

647 阅读1分钟

监听遥控器事件主要是通过RawKeyboardListener部件实现的,可以通过自定义部件来实现封装。

RawKeyboardListener 是通过继承 StatefulWidget 实现的,所以在调用时只能在 MaterialApp.body 或者是 children 中调用。

如果是调用

class MyRowKeyBrandListener extends StatelessWidget {
  Widget child;

  Function event;

  MyRowKeyBrandListener({required this.child, required this.event, Key? key}) : super(key: key);

  final FocusNode _textNode = FocusNode();

  handleKey(RawKeyEvent key) {
    debugPrint("Event runtimeType is ${key.runtimeType}");
    if(key.runtimeType.toString() == 'RawKeyDownEvent'){
      RawKeyEventDataAndroid data = key.data as RawKeyEventDataAndroid;
      String _keyCode;
      _keyCode = data.keyCode.toString(); //keycode of key event (66 is return)
      event();
      debugPrint("why does this run twice $_keyCode");
    }
  }

  @override
  Widget build(BuildContext context) {
    FocusScope.of(context).requestFocus(_textNode);

    return RawKeyboardListener(
        focusNode: _textNode,
        onKey: handleKey,
        child: child,
    );
  }
}

使用 InkWell 包裹部件才可以实现遥控器选中

Stack(
  children: [
    Container(
      color: Colors.white,
      padding: EdgeInsets.all(toRpx(context, 20)),
      child: Row(
        children: [
          _songCover(),
          _songContent(),
        ],
      ),
    ),
    Positioned.fill(
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          splashColor: Colors.white.withOpacity(.3),
          highlightColor: Colors.white.withOpacity(.1),
          onTap: () {
            debugPrint('tap');
          },
        ),
      ),
    )
  ],
)

循环构造 Listview , 通过复写 event 事件,触发

ListView.builder(
  itemCount: _songList.length,
  itemBuilder: (BuildContext context, int index) {
    return MyRowKeyBrandListener(child: Container(
        margin: const EdgeInsets.symmetric(vertical: 4),
        child: SongCard(data: _songList[index])
    ), event: (){
      debugPrint('index:$index');
    });
  },
)