首页 > 解决方案 > Flutter 自定义键盘(“假”软键盘)

问题描述

我正在开发一个金融应用程序,我想要一个自定义文本输入字段和键盘,用于使用内置计算器输入货币。

我尝试过使用持久性和模态的 BottomSheet。模态行为是理想的,但它总是显示出障碍。持久的就是我现在拥有的,使用焦点节点来显示和隐藏它,但它抛出了奇怪的错误:

I/flutter (30319): The following NoSuchMethodError was thrown while dispatching notifications for FocusNode:
I/flutter (30319): The method 'removeLocalHistoryEntry' was called on null.
I/flutter (30319): Receiver: null
I/flutter (30319): Tried calling: removeLocalHistoryEntry(Instance of 'LocalHistoryEntry')
I/flutter (30319):
I/flutter (30319): When the exception was thrown, this was the stack:
I/flutter (30319): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:46:5)
I/flutter (30319): #1      LocalHistoryEntry.remove (package:flutter/src/widgets/routes.dart:296:12)
I/flutter (30319): #2      _NumpadFieldState.initState.<anonymous closure> (file:///D:/code/financepie/lib/widgets/numpad/numpadfield.dart:30:32)
...

在任何情况下,底部的工作表行为(向下拖动)对于复制 android/ios 软键盘并不是很理想。有更好的解决方案吗?当前代码如下:

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

class NumpadField extends StatefulWidget {

  @override
  _NumpadFieldState createState() {
    return new _NumpadFieldState();
  }
}

class _NumpadFieldState extends State<NumpadField> {
  ValueNotifier<List<String>> state;
  FocusNode focusNode;
  PersistentBottomSheetController bottomSheetController;

  @override initState() {
    super.initState();
    state = ValueNotifier<List<String>>([]);
    state.addListener(() => setState((){}));
    focusNode = FocusNode();
    focusNode.addListener(() {
      print(focusNode);
      if (focusNode.hasFocus) {
        bottomSheetController = showBottomSheet(
          context: context,
          builder: (context) => Numpad(state: state),
        );
      } else {
        bottomSheetController?.close(); ///this line causing the error
      }
    }); 
  }
  @override dispose() {
    state.dispose();
    focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(focusNode);
      },
      child: Container(
        child: Text(state.value.fold<String>("", (str, e) => "$str $e")),
        constraints: BoxConstraints.expand(height: 24.0),
        decoration: BoxDecoration(
          border: BorderDirectional(bottom: BorderSide())
        ),
      ),
    );
  }
}

标签: androidioskeyboarddartflutter

解决方案


bottomSheetController?.close();可以为空。由于该行导致错误,您可以添加一个空检查来防止此问题。

else {
  if(bottomSheetController != null)
      bottomSheetController!.close();
}

推荐阅读