【发布时间】:2023-01-30 02:49:59
【问题描述】:
我想创建一个屏幕,其中许多 TextFIelds 垂直排列,当在编辑底部的 TextField 时按下 Enter 键时,一个新的 TextField 也会添加到它下面,同时移动焦点。我在 FocusNode 的文档中创建了一个引用 the example 的演示应用程序,它基本上可以工作,但是当将焦点移动到新创建的 TextField 时键盘会弹跳(参见下面的 gif)。我该如何解决这种不良行为?
演示应用程序的代码在这里:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int focusedChild = 0;
List<Widget> children = <Widget>[];
List<FocusNode> childFocusNodes = <FocusNode>[];
@override
void initState() {
super.initState();
// Add the first child.
_addChild();
}
@override
void dispose() {
for (final FocusNode node in childFocusNodes) {
node.dispose();
}
super.dispose();
}
void _addChild() {
// Calling requestFocus here creates a deferred request for focus, since the
// node is not yet part of the focus tree.
childFocusNodes
.add(FocusNode(debugLabel: 'Child ${children.length}')..requestFocus());
children.add(
TextField(
focusNode: childFocusNodes.last,
textInputAction: TextInputAction.unspecified,
minLines: 1,
onSubmitted: (value) {
setState(() {
focusedChild = children.length;
_addChild();
});
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: children,
),
),
),
);
}
}
【问题讨论】: