我正在向用户显示一个对话框,我想在单击对话框的正面按钮时更改对话框的标题但是我该怎么做。
由于对话框已在屏幕上显示,setState()
将无法执行任何操作。
码:
String title = "Old Title" // member variable
RaisedButton(onPressed: (){
showDialog(context: context, builder: (context) {
return AlertDialog(title: Text(title), actions: <Widget>[FlatButton(onPressed: () {
setState(() => title = "New Title");
}, child: Text("Change"))],);
});
}, child: Text("Change"),)
你可以创建一个返回StatefulWidget
的AlertDialog
。点击更改按钮时,setState
将更新对话框的文本值。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Dynamic Dialog',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Dynamic Dialog'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Press the FAB to present the dialog!',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: ((BuildContext context) {
return DynamicDialog(title: 'Original Title');
}));
},
tooltip: 'Show Dialog',
child: Icon(Icons.add),
),
);
}
}
class DynamicDialog extends StatefulWidget {
DynamicDialog({this.title});
final String title;
@override
_DynamicDialogState createState() => _DynamicDialogState();
}
class _DynamicDialogState extends State<DynamicDialog> {
String _title;
@override
void initState() {
_title = widget.title;
super.initState();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(_title),
actions: <Widget>[
FlatButton(
onPressed: () {
final newText = 'Updated Title!';
setState(() {
_title = newText;
});
},
child: Text('Change'))
],
);
}
}
您可以这样做 - 无需创建其他小部件
RaisedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
StreamController<String> controller = StreamController<String>.broadcast();
return AlertDialog(
title: StreamBuilder(
stream: controller.stream,
builder: (BuildContext context, AsyncSnapshot<String> snapshot){
return Text(snapshot.hasData ? snapshot.data : 'Title');
}),
actions: [
FlatButton(
onPressed: () {
controller.add('New Title');
},
child: Text('Change'))
],
);
});
},
child: Text('Change'),
);