【问题标题】:how to pass Context to show AlertDialog in flutter如何传递上下文以在颤动中显示 AlertDialog
【发布时间】:2020-05-11 22:01:38
【问题描述】:

我查看了SO question 以了解如何显示 AlertDialog,因此在 Android Studio 生成的启动应用程序中,我尝试过,但传递 BuildContext 是一个问题,所以另一个 SO answer 帮助了我。

但是在那之后仍然没有出现对话框,这里是代码。

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: 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;

  void _incrementCounter() {
     setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(

        child: Column(
           mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pressed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
     //   onPressed: _incrementCounter,
        onPressed: () => showAlertDialog,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }


  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 没有被触发。

【问题讨论】:

    标签: flutter


    【解决方案1】:

    问题是您没有将上下文传递给您的 showAlertDialog 函数,而是尝试将其称为 showAlertDialog(context)。

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2020-02-04
      • 1970-01-01
      相关资源
      最近更新 更多