Flutter 中的 AlertDialog 小部件无法使用 setState 功能
Posted
技术标签:
【中文标题】Flutter 中的 AlertDialog 小部件无法使用 setState 功能【英文标题】:AlertDialog widget not working setState function in Flutter 【发布时间】:2020-09-26 00:16:46 【问题描述】:我开始使用 DropdownButton 小部件并创建了城市列表。当我在列表中选择我最喜欢的城市时,我想看到 AlertDialog,但它无法工作。 这是代码:
import 'package:flutter/material.dart';
import './func.dart';
class ChooseCity extends StatefulWidget
@override
State<StatefulWidget> createState()
return ChooseCityState();
class ChooseCityState extends State<ChooseCity>
var cities = ["Ankara", "İzmir", "İstanbul", "Edirne", "Antalya"];
String choosenCity = "Edirne";
@override
Widget build(BuildContext context)
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<String>(
items: cities.map((String city)
return DropdownMenuItem<String>(
child: Text(city),
value: city,
);
).toList(),
value: choosenCity,
onChanged: (String choosen)
setState(()
choosenCity = choosen;);
choosen=="Antalya" ?
AlertDialog(
title:Text("ATTENTION"),
content: Text("You chose the best place!!"),
actions: [
FlatButton(child: Text("I see,I agree"),onPressed: ()=>,)
],
)
: Text("go on");
,
),
SizedBox(
height: 60,
),
Text(
" You choosed :" + choosenCity,
textAlign: TextAlign.center,
),
],
);
查看我的页面:
它看起来不像我想要的。当我选择 "Antalya" 时,我想看到 AlertDialog。错误在哪里?我应该把布尔函数放在哪里?我试图把这个 bool 函数从 setState 函数中去掉,但它不是我想要的。
【问题讨论】:
【参考方案1】:如果您想显示警报对话框,您应该使用“showDialog”,然后在其构建器中使用您的警报对话框。
这样
class ChooseCity extends StatefulWidget
@override
State<StatefulWidget> createState()
return ChooseCityState();
class ChooseCityState extends State<ChooseCity>
var cities = ["Ankara", "İzmir", "İstanbul", "Edirne", "Antalya"];
String chosenCity = "Edirne";
@override
Widget build(BuildContext context)
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<String>(
items: cities.map((String city)
return DropdownMenuItem<String>(
child: Text(city),
value: city,
);
).toList(),
value: chosenCity,
onChanged: (String choosen)
chosenCity = choosen;
showAlertDialog();
setState(() );
,
),
SizedBox(
height: 60,
),
Text(
" You choosed :" + chosenCity,
textAlign: TextAlign.center,
),
],
);
showAlertDialog()
showDialog(
context: context,
builder: (context)
return AlertDialog(
title: Text("ATTENTION"),
content: Text("You chose the best place!!"),
actions: [
FlatButton(
child: Text("I see,I agree"),
onPressed: () => ,
)
],
);
,
);
【讨论】:
此处发布的所有内容必须为英文。以上是关于Flutter 中的 AlertDialog 小部件无法使用 setState 功能的主要内容,如果未能解决你的问题,请参考以下文章
当 AlertDialog 中的复选框选中或未选中时,Flutter 更新 Reorderable ListView
如何在 Flutter 中将 AlertDialog FlatButton 居中