Flutter中获取焦点的方法
import 'package:flutter/material.dart';
class MyTextFiled extends StatefulWidget{
@override
State<StatefulWidget> createState() {
// TODO: implement createState
}
}
class _MyTextFiled extends State<MyTextFiled>{
TextEditingController _editController;
FocusNode _editFocusNode;
@override
void initState() {
// TODO: implement initState
super.initState();
_editController = new TextEditingController();
_editFocusNode = new FocusNode();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
FocusScope.of(context).requestFocus(_editFocusNode); // 自动聚焦
FocusScope.of(context).requestFocus(FocusNode());//去除焦点
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(title: Text('look'),),
body: Container(
margin: EdgeInsets.only(top: 50.0),
width: 400.0,
height: 45.0,
child: TextField(
controller: _editController,
focusNode: _editFocusNode,
),
),
);
}
}
FocusNode focusNode = FocusNode();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
FocusScope.of(context).requestFocus(focusNode); // 自动聚焦
});```
//方法一在进入界面自动弹出搜索框,如果过快弹出 会发生异常,可以改为 300毫秒后 弹出,
Future.delayed(Duration(milliseconds: 300), () {
focusNode.requestFocus();
});