import 'package:flutter/material.dart';
class Demo {
int no;
String value;
Demo({this.value, this.no});
}
class Control {
TextEditingController controller;
FocusNode node;
Control({this.controller, this.node});
}
class DemoPage extends StatefulWidget {
static const routeName = '/Demo';
DemoPage({Key key}) : super(key: key);
@override
_DemoPageState createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> {
List<Demo> txtfield;
List<Control> control;
@override
void initState() {
txtfield = [];
control = [];
// no = 0;
add();
super.initState();
}
int no;
void add() {
no = (no ?? 0) + 1;
setState(() {});
txtfield.add(Demo(no: no));
control.add(Control(
controller: TextEditingController(),
node: FocusNode(),
));
// no = no +1;
}
@override
Widget build(BuildContext context) {
// print(txtfield[0].no);
// FocusScope.of(context).requestFocus(control[control.length - 1].node);
return Scaffold(
appBar: AppBar(),
body: Center(
child: Card(
child: Container(
child: Column(
children: txtfield
.map((f) => TextField(
controller: control[f.no - 1].controller,
focusNode: control[f.no - 1].node,
autofocus: true,
))
.toList(),
),
width: 400,
padding: EdgeInsets.all(20),
),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
add();
print(no);
FocusScope.of(context).requestFocus(control[control.length - 1].node);
},
),
);
}
}
我使用了上面的代码。但我无法将注意力集中在新添加的文本字段上。当我检查新添加的文本字段是否有焦点时,它显示为true,但我不能在该文本字段中写入任何内容。
我不知道那个代码中有什么错误。我搜索此解决方案已超过4天。但我找不到解决办法。
在浮动ActionButton的onPressed
处更改此行:
FocusScope.of(context).requestFocus(control[control.length - 1].node);
用这个
control[control.length - 1].node.requestFocus();