我将焦点节点添加到textformfield。在将Flutteer版本升级到v1.12.13 + hotfix.5之后,flutter focusnode发生了意外的行为。
@override
void initState() {
super.initState();
focusNode.addListener(() async {
if(focusNode.hasFocus)
{
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
}
}
}
TextFormField(
style: TextStyle(color: Theme.of(context).brightness==Brightness.dark?Colors.white:Colors.grey),
readOnly: true,
validator: validateField,
focusNode: focusNode,
controller: controller,
);
我单击到textformfield来打开secondPage。但是当我关闭secondPage时,第二页会自动打开。我将版本升级到v1.12.13 + hotfix.5后,会发生此行为。
v1.12.13 + hotfix.5中focusNode的真正用法是什么?
答案 0 :(得分:1)
您可以在下面复制粘贴运行完整代码
因为从TextFormField
返回时foucs
仍然有SecondRoute
,所以您需要做unfocus
代码段
focusNode.addListener(() async {
if (focusNode.hasFocus) {
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
FocusScope.of(context).requestFocus(new FocusNode());
}
});
工作演示
完整代码
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
final controller = TextEditingController();
FocusNode focusNode = new FocusNode();
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
void initState() {
super.initState();
focusNode.addListener(() async {
if (focusNode.hasFocus) {
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
FocusScope.of(context).requestFocus(new FocusNode());
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
style: TextStyle(
color: Theme.of(context).brightness == Brightness.dark
? Colors.white
: Colors.grey),
readOnly: true,
//validator: validateField,
focusNode: focusNode,
controller: controller,
),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class SecondRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
);
}
}