【问题标题】:What is "BuildContext" in flutter means?, and how to use it?颤振中的“BuildContext”是什么意思?以及如何使用它?
【发布时间】:2022-01-21 09:43:02
【问题描述】:

我这里实现第三个代码有问题https://www.codegrepper.com/search.php?answer_removed=1&q=alert%20dialog%20aler%20dialog%20flutter

class _HomepageState extends State<Homepage> {
 @override
 void initState() {
   super.initState();
   setState(() {
     showAlertDialog();
   });
 }

 @override
 Widget build(BuildContext context) {
   return ListView(
     padding: EdgeInsets.all(20),
     children: <Widget>[
       Center(
         child: Text(
           'Welcome',
           style: TextStyle(fontSize: 30),
           textAlign: TextAlign.center,
         ),
       ),
       SizedBox(height: 30),
       Text(
         "News",
         style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
       ),
       SizedBox(height: 20),
     ],
   );
 }

 showAlertDialog(BuildContext context) {
   // set up the button
   Widget okButton = FlatButton(
     child: Text("OK"),
     onPressed: () {},
   );

   // set up the AlertDialog
   AlertDialog alert = AlertDialog(
     title: Text("My title"),
     content: Text("This is my message."),
     actions: [
       okButton,
     ],
   );

   // show the dialog
   showDialog(
     context: context,
     builder: (BuildContext context) {
       return alert;
     },
   );
 }
}

取消“showAlertDialog();”仍然是错误,因为它需要类型为“BuildContext”的参数

如果有其他方法,请告诉我,非常感谢

【问题讨论】:

  • 这能回答你的问题吗? How to make an AlertDialog in Flutter?
  • 我认为是不同的情况
  • 抱歉,我可能不太清楚,您所问问题的直接答案似乎是this question。但是,看看你的问题,你的最终目标似乎是学习如何在 Flutter 中显示警报对话框,在这种情况下,我上面链接的问题比你发送的问题更好。 Flutter 团队还发布了一个关于 BuildContext 的视频here 如果你想让示例正常运行,请将使用 context 的代码移到可以访问它的范围内,即构建方法。跨度>
  • 我明白了,非常感谢

标签: flutter flutter-layout


【解决方案1】:

事实证明,我必须将代码放在 Widget 构建(BuildContext 上下文)中,但在返回命令之外,所以我这对我有用(我还修改了对话框的功能)

 @override
 Widget build(BuildContext context) {
   if (int.parse(COUNTDAY) >= 5) {
     Future.delayed(Duration.zero, () => showAlert(context));
   }
   return ListView(
     padding: EdgeInsets.all(20),
     children: <Widget>[
       Center(
         child: Text(
           'Welcome',
           style: TextStyle(fontSize: 30),
           textAlign: TextAlign.center,
         ),
       ),
       SizedBox(height: 30),
       Text(
         "News",
         style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
       ),
       SizedBox(height: 20),
     ],
   );
 }

 showAlert(BuildContext context) {
   showDialog(
     context: context,
     builder: (context) => AlertDialog(
       content: Text(
         "Your time is up",
           style: TextStyle(fontSize: 25),
           textAlign: TextAlign.center,
         ),
       )
     );
   }

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 2012-09-12
    • 2021-11-19
    • 2011-04-23
    • 2010-11-22
    • 2015-02-02
    • 2016-02-26
    相关资源
    最近更新 更多