我正在尝试对处于横向视图的应用进行大头针登录。 我使用的是Dart / flutter,无法弄清楚如何重新定位文本输入键盘。
是否可以使用类似的方法,但是将键盘强制在文本字段的下一个而不是文本字段的下一个? How to create number input field in Flutter?
答案 0 :(得分:2)
键盘的位置和形状完全取决于设备。甚至还有浮动键盘或拆分键盘,也无法修改系统键盘的位置。
我建议您在Flutter中构建一个“假”数字键盘小部件。这样可以完全控制键盘的位置和大小以及显示的数字。对于简单的PIN输入,您甚至不需要将其连接到真实的TextField
,这使事情变得容易得多。
这是一个非常基本的示例:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyLoginPage(),
);
}
}
class MyLoginPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => MyLoginPageState();
}
class MyLoginPageState extends State<MyLoginPage> {
String _pin = '';
void _onKeyPressed(int key) {
if (key == NumericalKeyboard.backspaceKey) {
if (_pin.length > 0) {
setState(() {
_pin = _pin.substring(0, _pin.length - 1);
});
}
} else {
setState(() {
_pin += key.toString();
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('LOGIN'),
),
body: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(child: _buildPage()),
NumericalKeyboard(
onKeyPressed: _onKeyPressed,
)
],
),
);
}
Widget _buildPage() {
return Padding(
padding: EdgeInsets.all(16.0),
child: Center(
child: Container(
decoration: BoxDecoration(border: Border.all()),
width: 150.0,
padding: EdgeInsets.all(4.0),
child: Text(
_pin,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 32.0, letterSpacing: 2.0),
),
),
),
);
}
}
typedef KeyboardCallback(int key);
class NumericalKeyboard extends StatelessWidget {
const NumericalKeyboard({Key key, this.onKeyPressed}) : super(key: key);
static const backspaceKey = 42;
static const clearKey = 69;
final KeyboardCallback onKeyPressed;
@override
Widget build(BuildContext context) {
return Material(
color: Colors.grey[200],
child: Table(
defaultColumnWidth: IntrinsicColumnWidth(flex: 1.0),
border: TableBorder.all(),
children: [
TableRow(
children: [
_buildNumberKey(1),
_buildNumberKey(2),
_buildNumberKey(3),
],
),
TableRow(
children: [
_buildNumberKey(4),
_buildNumberKey(5),
_buildNumberKey(6),
],
),
TableRow(
children: [
_buildNumberKey(7),
_buildNumberKey(8),
_buildNumberKey(9),
],
),
TableRow(
children: [
Container(),
_buildNumberKey(0),
_buildKey(Icon(Icons.backspace), backspaceKey),
],
)
],
),
);
}
Widget _buildNumberKey(int n) {
return _buildKey(Text('$n'), n);
}
Widget _buildKey(Widget icon, int key) {
return IconButton(
icon: icon,
padding: EdgeInsets.all(16.0),
onPressed: () => onKeyPressed(key),
);
}
}