0

I have the follwing code with a _checkCreds function. I want to show an alert when that button is pressed.

When I replace the print() statement with an AlertDialog(), I get a "No MaterialLocalizations found".

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState(); 
}

class _MyAppState extends State<MyApp> {
  void _checkCreds(bool val) {
    if(!val){
      print("Warning, show alert here instead of print!");
      return;
    }
    ...
    // Continue executing
  }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: RaisedButton(
        child: "Press me to trigger an alert!" ),
        onPressed: () => _checkCreds(false),
    );   
  } 

}
usersina
  • 1,063
  • 11
  • 28

2 Answers2

2

I've figured it out, coming for a React environment I didn't know where "BuildContext" fits in all of this. After further investigation I passed the current context as an argument to the function that calls the Alert.

Above main():

Future<void> _ackAlert(BuildContext context) {
  return showDialog<void>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Error'),
        content: const Text('Please enter a valid text'),
        actions: <Widget>[
          FlatButton(
            child: Text('Okay'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },   
  ); 
}

Inside the main widget:

Widget build(BuildContext context) {
    return MaterialApp(
      home: RaisedButton(
        child: "Press me to trigger an alert!" ),
        // I've added a parameter that takes the current context
        onPressed: () => _checkCreds(false, context),
    );   
  } 
usersina
  • 1,063
  • 11
  • 28
1

I think this is what you want:

void _checkCreds(bool val){//put it inside 'MyAppState' class
  if(!val){
    showDialog(
      barrierDismissible: true,//tapping outside dialog will close the dialog if set 'true'
      context: context, 
      builder: (context){
        return Dialog(
          //Add code here
        );
      }
    );
  }
  ...
  // Continue executing
}

AlertDialog and Dialog has same properties except AlertDialog has content property whereas Dialog has child property. Both does same work.

littleironical
  • 1,593
  • 1
  • 11
  • 25
  • The problem wasn't the Alert in itself, however the fact that it needs a "context" which should be passed to the function: _checkCreds(bool val, BuildContext context). If I pass the context in the button OnPressed, the issue is solved. – usersina Jul 24 '20 at 19:16