我正在参加「启航计划」
前语
Flutter在桌面设备的实践,咱们现已落地了多个项目,充沛验证其技术和事务的可行性。一起也对Flutter提出了更多的要求,其中就包含:遥控器的适配!
很惋惜,Flutter官方底子没有考虑过遥控器的适配,甚至其焦点操控还有不少问题【比方:切换闪烁、快速操作下焦点无法呼应】,因而咱们必须自己打破这个壁垒。
遥控器怎么玩?
遥控器在软件层面其实便是按键事情,相当于咱们的键盘。Android本身有TV设备,因而现已有一套完善的操控机制。
在Android中,咱们只需求对view声明能够获取焦点,指定焦点联系即可
。结构会帮咱们主动聚集到对应的控件上;简单的UI状况用一个SelectDrawable就能够处理。
对比Flutter这种声明式UI,Android命名式UI有天然的优势,经过生成的R文件,结构层能够经过FocusFinder容易的找到对应的view,处理好焦点的分发流通和事情处理。
Flutter遥控器的难点
- Flutter是声明式UI,在编译时要生成资源类本身就比较困难;
- Widget仅仅配置信息,咱们在开发过程中想要拿到控件的信息必须经过Key值去获取Rander对象,要获取各组件的信息来确定方向、执行事情是非常费事的;
- 经过实践,咱们发现Flutter focusNode还存在不少问题,请求过程偶发焦点重复request,快速切换焦点会呼应过错;在Android设备上更加明显;
- Flutter的Material组件库有部分控件是自己持有focusNode的,默认会本身呼应键盘事情,这会跟咱们自己的焦点办理发生抵触。
完成原理
摒弃Flutter自带的FoucusNode流通机制,由于Flutter压根就没帮咱们做好这层流通。
自行监听事情,进行焦点分发,事务端自行加入ControlManager,清晰知道当时哪个焦点被触发。
完成过程
1. 大局的遥控事情接纳组件
已然Flutter无法轻松的生成焦点的流通联系,那咱们就自行处理,定义一个大局的事情接纳器。这个组件需求接纳一个child,一般把MaterialApp
传入。
组件内部接纳按键事情,解析后进行事情分发。
class ControlApp extends StatelessWidget {
ControlApp({Key? key, required this.app}) : super(key: key);
final Widget app;
final FocusNode remoteControl = FocusNode(debugLabel: 'Flutter遥控器');
final EventBus _eventBus = EventBus.instance;
@override
Widget build(BuildContext context) {
return RawKeyboardListener(
onKey: (RawKeyEvent event) {
if (event is RawKeyDownEvent) {
RawKeyEventDataWindows rawKeyEventData =
event.data as RawKeyEventDataWindows;
switch (rawKeyEventData.keyCode) {
case 38: //KEY_UP
_eventBus.fire(EventType.up);
break;
case 40: //KEY_DOWN
_eventBus.fire(EventType.down);
break;
case 37: //KEY_LEFT
_eventBus.fire(EventType.left);
break;
case 39: //KEY_RIGHT
_eventBus.fire(EventType.right);
break;
case 13: //KEY_ENTER
_eventBus.fire(EventType.enter);
break;
case 8: //KEY_BACK
_eventBus.fire(EventType.back);
break;
default:
break;
}
}
},
focusNode: remoteControl,
child: app,
);
}
}
2. 统一焦点接纳类办理
ControlApp
统一分发后,ControlManager
会进行接纳,一起ControlManager
将办理所有的遥控器监听者,供给addListener
、removeListener
、syncFocusKey
、changeTopFocus
等接口;保证遥控事情只发送给最终加入的监听者。
final controlManager = ControlManager.instance;
class ControlManager {
ControlManager._() {
initEventListen();
}
static final ControlManager instance = ControlManager._();
final EventBus _eventBus = EventBus.instance;
final ObserverList<ControlListener> _listeners =
ObserverList<ControlListener>();
bool receiveEvents = true;
int _currListenerIndex = 0;
// 记载所有listener的焦点调集
final List<List<FocusCollection>> _allCollectionList = [];
// 记载每个listener挑选的焦点调集
final List<FocusCollection?> _selectedCollectionList = [];
void addListener(ControlListener listener,
{required List<FocusCollection> focusList}) {
_listeners.add(listener);
_allCollectionList.add(focusList);
_currListenerIndex++;
_selectedCollectionList.add(null);
}
void removeListener(ControlListener listener) {
_listeners.remove(listener);
_selectedCollectionList.removeLast();
_allCollectionList.removeLast();
_currListenerIndex--;
}
/// 修正顶层焦点调集
void changeTopFocus(List<FocusCollection> focusList,
{FocusCollection? curr}) {
_allCollectionList.last = focusList;
if (curr == null) {
_selectedCollectionList[_currListenerIndex - 1] = null;
_listeners.last.onCancelSelect();
} else {
_selectedCollectionList[_currListenerIndex - 1] = curr;
_listeners.last.onWidgetSelect(curr);
}
}
/// 是否暂停处理遥控器事情
setReceiveStatus(bool isReceive) {
receiveEvents = isReceive;
}
/// 同步焦点的建值
syncFocusKey(FocusCollection focus) {
_selectedCollectionList[_currListenerIndex - 1] = focus;
}
bool get focusIsEmpty => _allCollectionList[_currListenerIndex - 1].isEmpty;
initEventListen() {
_eventBus.on().listen((event) {
if (!receiveEvents) return;
switch (event) {
case EventType.up:
case EventType.left:
if (focusIsEmpty) return;
_listeners.last.onWidgetSelect(getFocusCollection(event));
break;
case EventType.enter:
if (focusIsEmpty) return;
if (_selectedCollectionList[_currListenerIndex - 1] == null) return;
_listeners.last.onEnterEvent(getFocusCollection(event));
break;
case EventType.down:
case EventType.right:
if (focusIsEmpty) return;
_listeners.last.onWidgetSelect(getFocusCollection(event));
break;
case EventType.back:
if (focusIsEmpty) {
_listeners.last.onBackEvent(null);
} else {
_listeners.last.onBackEvent(getFocusCollection(event));
}
break;
}
});
}
/// 获取命中的焦点调集
FocusCollection getFocusCollection(EventType type) {
if (_selectedCollectionList[_currListenerIndex - 1] == null) {
var c = _allCollectionList[_currListenerIndex - 1].first;
_selectedCollectionList[_currListenerIndex - 1] = c;
return c;
} else {
FocusCollection c = _selectedCollectionList[_currListenerIndex - 1]!;
List<FocusCollection> l = _allCollectionList[_currListenerIndex - 1];
switch (type) {
case EventType.up:
if (c.up != null) c = l.firstWhere((e) => e.currKey == c.up);
break;
case EventType.down:
if (c.down != null) c = l.firstWhere((e) => e.currKey == c.down);
break;
case EventType.left:
if (c.left != null) c = l.firstWhere((e) => e.currKey == c.left);
break;
case EventType.right:
if (c.right != null) c = l.firstWhere((e) => e.currKey == c.right);
break;
case EventType.enter:
case EventType.back:
break;
}
_selectedCollectionList[_currListenerIndex - 1] = c;
return c;
}
}
}
3. 供给遥控器监听抽象类
需求监听遥控事情的页面(或组件),需求混入这个类,然后在对应生命钩子中调用ControlManager
中的addListener和removeListener事情。
abstract class ControlListener {
void onWidgetSelect(FocusCollection collection) {}
void onCancelSelect() {}
void onEnterEvent(FocusCollection collection) {}
void onBackEvent(FocusCollection? collection) {}
}
重写ControlListener中供给的接口,就能准确接纳到ControlManager发出的事情拉!
class _MyHomePageState extends State<MyHomePage> with ControlListener {
int _counter = 0;
String selectKey = ""; // 挑选的焦点key
// 自行保护焦点的联系
List<FocusCollection> focusList = [
FocusCollection("one", right: "two", down: "three"),
FocusCollection("two", left: "three", up: "one"),
FocusCollection("three", up: "one", right: "two")
];
@override
void initState() {
super.initState();
controlManager.addListener(this, focusList: focusList);
}
@override
void dispose() {
super.dispose();
controlManager.removeListener(this);
}
@override
void onWidgetSelect(FocusCollection collection) {
super.onWidgetSelect(collection);
setState(() {
selectKey = collection.currKey;
});
print(">>>>> onWidgetSelect ${collection.currKey}");
}
@override
void onBackEvent(FocusCollection? collection) {
super.onBackEvent(collection);
print(">>>>> onBackEvent ${collection?.currKey}");
}
@override
void onEnterEvent(FocusCollection collection) {
super.onEnterEvent(collection);
int i = focusList.indexOf(collection);
if (i == 2) {
_incrementCounter();
} else if (i == 0) {
Navigator.push(
context, MaterialPageRoute(builder: (context) => SecondPage()));
}
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(children: [
Positioned(
top: 20,
left: 20,
child: FocusWidget(
hasFocus: selectKey == "one",
child: const Text('You have pushed the button this many times:'),
),
),
Positioned(
top: 60,
right: 20,
child: FocusWidget(
hasFocus: selectKey == "two",
child: Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
),
),
Positioned(
top: 60,
left: 20,
child: FocusWidget(
hasFocus: selectKey == "three",
child: GestureDetector(
onTap: _incrementCounter,
child: Icon(Icons.add, color: Theme.of(context).primaryColor),
),
),
),
]),
);
}
}
- 从上面的比方能够看到,事务端是需求供给焦点列表,自行指定好上下左右的焦点关键字;这个过程其实就跟Android中,在xml指定焦点联系相同。
android:nextFocusDown="@id/button1"
android:nextFocusUp="@id/button2"
android:nextFocusLeft="@id/button3"
android:nextFocusRight="@id/button4"
- 一起比方中也有FocusWidget这个控件,我现在是彻底抛弃了Flutter自带的这套FoucusNode,而是清晰告诉Widget你被选中了、被点击了。这能处理FoucusNode本身的一些缺点。
- 当遇到带有FocusNode的组件,比方Input、Button、InkWell等,请一定要自主传入FoucusNode,而且设置skipTraversal为true,这样这个焦点就不会主动接纳键盘事情,不会导致焦点抵触。
FocusNode focusNode_1 = FocusNode(skipTraversal: true);
继续优化
在上面的计划中,咱们发现一个最经过的点便是:接入相对杂乱,特别是点击事情还要由页面等级告诉到对应组件自行去执行。对于封装程度高的项目,这是很致命的。
因而咱们把FocusWidget抽象出来,页面等级不再保护杂乱的焦点联系列表
;而是在需求处理焦点的控件外部包裹FocusWidget,传入需求的focus、nextFocusDown、nextFocusUp、nextFocusLeft、nextFocusRight;以及需求的UI状况、点击事情等。
之后遥控器插件会主动找寻对应的FocusWidget,显现其选中状况,并触发传入的点击事情!
将焦点联系和事情处理彻底融合在一起,不需求独自声明和保护,从而快速的让咱们的使用适配遥控器 ~
写在最终
这个计划现在在事务上现已得到实践认可,但是细节以及优化计划还有许多需求注意的。
总之遥控器在Flutter上是个相对难啃的坑,只能不断往前爬,往前填。