简体   繁体   中英

I have a variable and I want to display a dialog box when press the button flutter dart

I have a variable and I want to display dialog box when press the button flutter dart, but the content of the dialog box it will be changed according of the value of the variable, or create more then one dialog box and when I press the button one of them displayed according of the variable.

I want to ask for code if anyone can help me; the dart code I mean.

The variable is called som and calculates the median of 10 values.

  • if the sum == 0 -> then the button should display the first dialog box
  • else -> the button display the second dialog box

There are multiple ways you can achieve this.

  1. You can create multiple dialog boxes and do the condition checking on button tap by using switch or if. In the below code I have compared the values on the button tap and then return a function based on the value.

     class CustomAlerts extends StatelessWidget { final int som = 1; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Custom Dialog"), ), body: Container( child: Column( children: [ ElevatedButton( onPressed: () { if (som == 0) { showFirstDialog(context, som); } else { showSecondDialog(context, som); } }, child: Text("Button 1"), ), ], ), ), ); } showFirstDialog(BuildContext context, int value) { return showDialog( context: context, builder: (context) { return AlertDialog( title: Text("value is $value"), ); }); } showSecondDialog(BuildContext context, int value) { return showDialog( context: context, builder: (context) { return AlertDialog( title: Text("value is not equal to 0"), content: Text("value is $value"), ); }); } }
  2. You can check the value in the dialog box method and then return various alertboxes from there based on value.

     class CustomAlerts extends StatelessWidget { final int som = 1; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Custom Dialog"), ), body: Container( child: Column( children: [ ElevatedButton( onPressed: () { showCustomDialog(context, som); }, child: Text("Button 1"), ), ], ), ), ); } showCustomDialog(BuildContext context, int value) { if (value == 0) { return showDialog( context: context, builder: (context) { return AlertDialog( title: Text("value is $value"), ); }); } else { return showDialog( context: context, builder: (context) { return AlertDialog( title: Text("value is not equal to 0"), content: Text("value is $value"), ); }); } } }

Here I have compared the value inside a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM