@override
Widget build(BuildContext context) => MaterialApp(
title: ‘Flutter TextField Key Binding Demo’,
home: Scaffold(body: UnforgivingTextField()),
);
}
/// A text field that clears itself if the user tries to back up or correct
/// something.
class UnforgivingTextField extends StatefulWidget {
@override
State createState() => _UnforgivingTextFieldState();
}
class _UnforgivingTextFieldState extends State {
// The text editing controller used to clear the text field.
late TextEditingController controller;
@override
void initState() {
super.initState();
controller = TextEditingController();
}
@override
Widget build(BuildContext context) => Shortcuts(
shortcuts: <LogicalKeySet, Intent>{
// This overrides the left arrow key binding that the text field normally
// has in order to move the cursor back by a character. The default is
// created by the MaterialApp, which has a DefaultTextEditingShortcuts
// widget in it.
LogicalKeySet(LogicalKeyboardKey.arrowLeft): const ClearIntent(),
// This binds the delete and backspace keys to also clear the text field.
// You can bind any key, not just those already bound in
// DefaultTextEditingShortcuts.
LogicalKeySet(LogicalKeyboardKey.delete): const ClearIntent(),
LogicalKeySet(LogicalKeyboardKey.backspace): const ClearIntent(),
},
child: Actions(
actions: <Type, Action>{
// This binds the intent that indicates clearing a text field to the
// action that does the clearing.
ClearIntent: ClearAction(controller: controller),
},
child: Center(child: TextField(controller: controller)),
),
);
}
/// An intent that is bound to ClearAction.
class ClearIntent extends Intent {
const ClearIntent();
}
/// An action that is bound to ClearIntent that clears the TextEditingController
/// passed to it.
class ClearAction extends Action {
ClearAction({required this.controller});
final TextEditingController controller;
@override
Object? invoke(covariant ClearIntent intent) {
controller.clear();
}
}
自动滚动行为
实际显示滚动条时 Android 和 iOS 的逻辑是相同的,而对于桌面应用程序,当内容大于容器时通常会自动显示滚动条,这需要添加 Scrollbar
作为父 Widget
,为了在手机或 PC 上都能正常,此版本Scrollbar
会在必要时会自动添加。
例如下面所示的无滚动条的代码:
import ‘package:flutter/material.dart’;
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
title: ‘Automatic Scrollbars’,
home: HomePage(),
);
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
body: ListView.builder(
itemCount: 100,
itemBuilder: (context, index) => Text(‘Item $index’),
),
);
}
在桌面上运行它时,将显示一个滚动条:
如果你不喜欢滚动条的外观或始终显示滚动条的逻辑,可以设置一个 ScrollBarTheme
,则可以在整个应用范围内或在特定实例上,通过设置来更改它 ScrollBehavior
来完成修改。