Dialog中需要使用输入框,新建类继承自AlertDialog,使用时发现,键盘一直闪烁。
class TextFiledWrongDialog extends AlertDialog {
final GlobalKey<FormFieldState<String>> _passwordFieldKey = GlobalKey<FormFieldState<String>>();
@override
Widget get content => Material(
child: Wrap(
children: <Widget>[
Column(
children: <Widget>[
Text("Test Wrong Dialog"),
TextFormField(
key: _passwordFieldKey,
autofocus: true,
)
],
)
],
),
);
}
原因是AlertDialog继承自StatelessWidget,而事实上需要状态改变,所以必须将content变成StatefulWidget。
class AlertDialog extends StatelessWidget
完整示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Demo'),
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text("Show Wrong dialog"),
onPressed: () {
showDialog(context: context, builder: (_) => TextFiledWrongDialog());
},
),
RaisedButton(
child: Text("Show Right dialog"),
onPressed: () {
showDialog(context: context, builder: (_) => TextFiledRightDialog());
},
)
],
),
);
}
}
class TextFiledWrongDialog extends AlertDialog {
final GlobalKey<FormFieldState<String>> _passwordFieldKey = GlobalKey<FormFieldState<String>>();
@override
Widget get content => Material(
child: Wrap(
children: <Widget>[
Column(
children: <Widget>[
Text("Test Wrong Dialog"),
TextFormField(
key: _passwordFieldKey,
autofocus: true,
)
],
)
],
),
);
}
class TextFiledRightDialog extends AlertDialog {
final GlobalKey<FormFieldState<String>> _passwordFieldKey = GlobalKey<FormFieldState<String>>();
@override
Widget get content => DialogContent();
}
class DialogContent extends StatefulWidget {
@override
State<StatefulWidget> createState() => DialogContentState();
}
class DialogContentState extends State<DialogContent> {
final GlobalKey<FormFieldState<String>> _passwordFieldKey = GlobalKey<FormFieldState<String>>();
@override
Widget build(BuildContext context) {
return Material(
child: Wrap(
children: <Widget>[
Column(
children: <Widget>[
Text("Test Right Dialog"),
TextFormField(
key: _passwordFieldKey,
autofocus: true,
)
],
)
],
),
);
}
}