Ad

Flutter, Show AlertDialog From Function

- 1 answer

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),
    );   
  } 

}
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad