How to enable and disable button in GridView using Flutter? - android

I have created buttons in grid view using flutter. Now I want to change color of button when I click on button. Same like active use in HTML. When I click on button then button should be show in active state and when I click on another button then first button will be disable and current button will be enable.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'My Mitsu',
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white,
actions: <Widget>[
new RaisedButton(
child: new Text("Logout",
style: TextStyle(color: Colors.black, fontSize: 20.0)),
onPressed: () async {
log_out();
},
color: Colors.white,
)
],
),
backgroundColor: Colors.white,
body: Column(children: [
Expanded(
child: GridView.count(
crossAxisCount: countValue,
mainAxisSpacing: 35.0,
crossAxisSpacing: 35.0,
padding: const EdgeInsets.fromLTRB(20.0, 40.0, 40.0, 20.0),
childAspectRatio: (aspectWidth / aspectHeight),
children: <Widget>[
RaisedButton(
child: Text('Send Lift to Parking',
style: TextStyle(fontSize: 15.0)),
onPressed: () {
onPress(0);
showShortToast();
},
),
RaisedButton(
onPressed: () {
onPress(1);
showShortToast();
},
child: Text('Send Lift to 1st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(2);
showShortToast();
},
child: Text('Send Lift to 2st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(3);
showShortToast();
},
child: Text('Send Lift to 3st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(4);
showShortToast();
},
child: Text('Send Lift to 4st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(5);
showShortToast();
},
child: Text('Send Lift to 5st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(6);
showShortToast();
},
child: Text('Send Lift to 6st Floor',
style: TextStyle(fontSize: 15.0)),
),
RaisedButton(
onPressed: () {
onPress(7);
showShortToast();
},
child: Text('Send Lift to 7st Floor',
style: TextStyle(fontSize: 15.0)),
),
],
),
),
]));
}

if you don't pass a function to the onPressed property of the button, the button will be automatically disabled,
(don't pass = passing null)
///button#1
FlatButton(
//change color according to state
color: button1Enabled? Colors.green:Colors.red;
onPressed: button1Enabled? (){ } : null;
)
///button#2
FlatButton(
onPressed: (){
setState(){
button1Enabled = !button1Enabled;
}
}
)

Create you button like this
RaisedButton(
onPressed: () {
onPressed(1);
},
color: currentIndex == 1 ? bottonColor : null,
child: Text('Send Lift to 1st Floor',
style: TextStyle(fontSize: 15.0)),
),
and create onPress fuction like this
onPressed(String floor) {
setState(() {
currentIndex = int.parse(floor);
bottonColor = Colors.red;
});
}
create two variable outside the class currentIndex and buttonColor
int currentIndex = 0;
Color bottonColor;
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
}
}

Related

How to make sub-categories on flutter

I am giving an example when I click on the category group (fertilizer, medicine, etc.) that appears in the current picture, it will show 4 sub-categories, of course, it will be closed when I press it again. How can I do this in the most convenient way? Thank you everyone in advance
I am giving an example when I click on the category group (fertilizer, medicine, etc.) that appears in the current picture, it will show 4 sub-categories, of course, it will be closed when I press it again. How can I do this in the most convenient way? Thank you everyone in advance
Container(
alignment: Alignment.center,
padding: EdgeInsets.only(left: Dimensions.width10),
child: Flex(
direction: Axis.horizontal,
children: [Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
TextButton.icon(
onPressed: () {
setState(() {
_selectedPage = Page.el_makasi;
});
},
icon: Icon(
Icons.arrow_drop_down,
color:
_selectedPage == Page.el_makasi ? active : notActive,
),
label: const Text(
"Tohum",
style: TextStyle(color: AppColor.mainColor),
),
),
TextButton.icon(
onPressed: () {
setState(() {
_selectedPage = Page.gubre;
});
},
icon: Icon(
Icons.arrow_drop_down,
color: _selectedPage == Page.gubre ? active : notActive,
),
label: const Text("Gübre",
style: TextStyle(color: AppColor.mainColor)),
),
TextButton.icon(
onPressed: () {
setState(() {
_selectedPage = Page.ilac;
});
},
icon: Icon(
Icons.arrow_drop_down,
color: _selectedPage == Page.ilac ? active : notActive,
),
label: const Text("İlaç",
style: TextStyle(color: AppColor.mainColor)),
),
TextButton.icon(
onPressed: () {
setState(() {
_selectedPage = Page.tohum;
});
},
icon: Icon(
Icons.arrow_drop_down,
color: _selectedPage == Page.tohum ? active : notActive,
),
label: const Text("Makineler",
style: TextStyle(color: AppColor.mainColor)),
),
TextButton.icon(
onPressed: () {
setState(() {
_selectedPage = Page.makine;
});
},
icon: Icon(
Icons.arrow_drop_down,
color: _selectedPage == Page.makine ? active : notActive,
),
label: const Text("El makası",
style: TextStyle(color: AppColor.mainColor)),
),
],
),
),
),]
),
),
make a list within pages and select them with index in onPressed.
ExpansionTile is the best way to do this thing in an effective manner.
ExpansionTile(
title: Text("Ilac",
style: TextStyle(color:AppColor.mainColor)),
children: [
// here show 4 sub-categories, as pre UI design
Container(),
Container(),
],
),

How favorite list stays the same when you exit the application in flutter?

I created a database with sqflite on the user's phone. The words entered by the user are saved in the main list.
When you press the icon next to it, it is added to the favorite list, but when the user exits the application, the favorite list is reset.
The main list is the same, there is no problem with it.
When a word is deleted from the main list, it is also deleted from the favorite. But the only problem is that when the favorite list comes out and enters, it resets and writes blank.
How can I make the favorite list stay the same when I exit the application?
This is home page dart file.
class WordList extends StatefulWidget {
const WordList({Key key}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _WordListState();
}
}
class _WordListState extends State {
var dbHelper = DbHelper();
List<Word> words;
List<Word> favoriteWords = [];
int wordCount = 0;
int fwordCount = 0;
#override
void initState() {
getWords();
}
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: Text(
"ShopList",
style: GoogleFonts.caveat(
textStyle: const TextStyle(
color: Colors.white,
fontSize: 35,
letterSpacing: 1,
fontWeight: FontWeight.w700,
),
),
),
leading: const Padding(
padding: EdgeInsets.all(2.0),
child: Icon(
Icons.shopping_cart,
size: 35.0,
),
),
backgroundColor: Colors.deepPurple,
bottom: const TabBar(
indicatorColor: Colors.deepPurpleAccent,
automaticIndicatorColorAdjustment: false,
labelColor: Colors.deepPurple,
unselectedLabelColor: Colors.white,
indicatorSize: TabBarIndicatorSize.label,
indicator: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(7), topRight: Radius.circular(7)),
color: Colors.white),
tabs: [
Tab(
child: Align(
alignment: Alignment.center,
child: Icon(Icons.article_rounded),
),
),
Tab(
child: Align(
alignment: Alignment.center,
child: Icon(Icons.favorite),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
goToWordAdd();
},
child: const Icon(Icons.add),
tooltip: "Add New Item",
splashColor: Colors.white,
backgroundColor: Colors.deepPurple,
),
body: TabBarView(
children: [
ListView.builder(
itemCount: wordCount,
itemBuilder: (BuildContext context, int position) {
return Card(
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(3.0),
child: ListTile(
title: SelectableText(
words[position].word,
cursorColor: Colors.purple,
showCursor: false,
toolbarOptions: const ToolbarOptions(
copy: true,
selectAll: true,
cut: false,
paste: false),
style: GoogleFonts.caveat(
textStyle: const TextStyle(
color: Colors.deepPurple,
fontSize: 25.0,
fontWeight: FontWeight.w700,
),
),
),
subtitle: SelectableText(
words[position].description,
cursorColor: Colors.purple,
showCursor: false,
toolbarOptions: const ToolbarOptions(
copy: true,
selectAll: true,
cut: false,
paste: false),
style: GoogleFonts.caveat(
textStyle: const TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w700,
),
),
),
),
),
),
ElevatedButton(
onPressed: () {
setState(() {
if (!favoriteWords
.contains(words[position])) {
favoriteWords.add(words[position]);
}
});
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
Colors.deepPurple,
),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(5.0),
side: const BorderSide(
color:
Colors.deepPurpleAccent)))),
child: const Icon(
Icons.favorite,
color: Colors.white,
),
),
IconButton(
color: Colors.blueGrey,
icon: const Icon(Icons.delete),
tooltip: 'Delete Item',
onPressed: () {
goToDelete(words[position]);
},
),
],
),
);
},
),
favoriteWords.isEmpty
? const Center(
child: Text(
'Ürünlerini favorilerine ekle, almayı unutma! ',
style: TextStyle(
color: Colors.deepPurple,
fontWeight: FontWeight.bold),
),
)
: ListView.builder(
itemCount: fwordCount,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(3.0),
child: ListTile(
title: SelectableText(
favoriteWords[index].word,
cursorColor: Colors.purple,
showCursor: false,
toolbarOptions: const ToolbarOptions(
copy: true,
selectAll: true,
cut: false,
paste: false),
style: const TextStyle(fontSize: 17.0),
),
subtitle: SelectableText(
favoriteWords[index].description,
cursorColor: Colors.purple,
showCursor: false,
toolbarOptions: const ToolbarOptions(
copy: true,
selectAll: true,
cut: false,
paste: false),
style: const TextStyle(fontSize: 17.0),
),
),
),
),
ElevatedButton(
onPressed: () {
setState(() {
favoriteWords.remove(favoriteWords[index]);
});
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
Colors.deepPurple,
),
),
child: const Icon(
Icons.remove,
color: Colors.white,
),
),
],
),
);
},
),
],
),
),
);
}
void goToWordAdd() async {
bool result = await Navigator.push(
context, MaterialPageRoute(builder: (context) => const WordAdd()));
if (result != null) {
if (result) {
getWords();
}
}
}
void getWords() {
var wordsFuture = dbHelper.getWords();
wordsFuture.then((data) {
setState(() {
words = data;
wordCount = data.length;
});
});
}
void goToDelete(Word word) async {
await dbHelper.delete(word.id);
favoriteWords.remove(word);
getWords();
}
}

How can I add a container widget by pressing the button?

As shown in the picture below, there is a container widget with image and text field, and I would like to create an additional container when I click the button.
I have no idea how to implement this.
Can you suggest a way to implement this?
Container _productForm() {
return Container(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_productImage(),
_productImage(),
],
),
_heightPadding(15),
_inputText("input text", _controller2),
_heightPadding(15),
_inputText("input text", _controller3),
],
),
);
}
Widget _inputText(String hint, TextEditingController textEditingController) {
return Container(
width: double.infinity,
// height: 200,
child: TextField(
controller: textEditingController,
//엔터키 이벤트
onSubmitted: (value) {},
//높이를 부모 위젯의 높이로 설정 (컨테이너 전체를 텍스트필드로 사용)
// expands: true,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
),
hintText: hint,
),
),
);
}
Widget _addButton() {
return Container(
width: 200,
height: 65,
child: ElevatedButton(
onPressed: () {
//상품썸네일 아래에 상품썸네일 하나 더 추가
},
child: Text(
'Add Container',
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold),
),
style: ElevatedButton.styleFrom(
primary: Colors.blue, // background
onPrimary: Colors.white, // foregro// und
),
),
);
}
try put in the List:
List<Container> _containers = [_productForm(),_productForm(),];
onPressed: () {
//상품썸네일 아래에 상품썸네일 하나 더 추가
_containers.add(_productForm());
setState((){});
},
then Load your _containers list with ListView
create list of widget
List<Container> _containers = [_productForm(),_productForm(),];
set dynamic children in row
Row(
children: _containers
.map((_) => _productForm())
.toList(),
)
on press of your button
onPressed: () {
_containers.add(_productForm());
setState((){});
},

something problem on alertdialog flutter, you can help me?

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The getter 'modalBarrierDismissLabel' was called on null.
This is code
....
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(28.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
FlatButton(
child: Text(
"Booking Antrian",
style: TextStyle(color: Colors.white),
),
color: Colors.indigo,
onPressed: () {
createInterstitialAd()
..load()
..show();
},
),
FlatButton(
child: Text(
"Keluar",
style: TextStyle(color: Colors.white),
),
color: Colors.green,
onPressed: () {
createInterstitialAd()
..load()
..show();
},
),
FlatButton(
child: Text(
"About",
style: TextStyle(color: Colors.white),
),
color: Colors.pink,
onPressed: () {
createInterstitialAd()
..load()
..show();
},
),
RaisedButton(
child: Text('Alert with Buttons'),
onPressed: () => _onAlertButtonsPressed(context),
),
],
),
),
);
}
...
_onAlertButtonsPressed(context) {
Alert(
context: context,
//image: Image.network('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
image: Image.asset(
'assets/images/watermark.jpg',
width: 100.0,
height: 100.0,
),
title: "RE",
desc: "Halo.. 😊",
buttons: [
DialogButton(
child: Text(
"Close",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () => Navigator.pop(context),
color: Color.fromRGBO(231, 76, 60, 10),
),
DialogButton(
child: Text(
"Share",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () => Navigator.pop(context),
color: Color.fromRGBO(0, 179, 134, 1.0),
),
],
).show();
}
...
in your app delegates add this:
GlobalCupertinoLocalizations.delegate
So in your main MaterialApp Widget:
MaterialApp(
...
localizationsDelegates: [
// A class which loads the translations from JSON files
AppLocalizations.delegate,
// Built-in localization of basic text for Material widgets
GlobalMaterialLocalizations.delegate,
// Built-in localization for text direction LTR/RTL
GlobalWidgetsLocalizations.delegate,
// Built-in localization of basic text for Cupertino widgets
GlobalCupertinoLocalizations.delegate
],
)

I am trying to put gesture dectector in the alert dialog to navigate to next page but the alert box overflows

I am not using any button in alert dialog, so in action how can we prevent the overflow the alert dialog, if am using gesture detector or inkwell to get ontap or onpress function or is there any other method to do it
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
content: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
Container(
child: new GestureDetector(
onTap:(){
Navigator.push(context,
MaterialPageRoute(builder: (context) => ThirdRoute()));
} ,
),
),
]
);
});
}
You are getting overflow error due to GestureDetector used inside actions property of the dialog. If you just want user to tap anywhere on the alertDialog, you can wrap the AlertDialog with GestureDetector. With this, when user taps anywhere on the dialog, it will navigate them to thirdRoute. Working code below:
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return GestureDetector(
child: AlertDialog(
title:
Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
)
],
),
content:
Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 15.0)),
// gradient: LinearGradient(
// colors: <Color>[
// Color(0xDD4a00e0),
// Color(0xFF8e2de2),
// ],
// begin: Alignment.topCenter,
// end: Alignment.bottomCenter,
// ),
actions: <Widget>[]
),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => NextScreen()));
}
);
});
}
Hope this answers your question.
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return GestureDetector(
child: UnicornAlertDialog(
title: Column(
children: <Widget>[
Container(
child: Image.asset('images/done.png'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
content: Text(
'You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[ ]),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => ThirdRoute()));
},
);
});
}
Unicorn alert dialog is used for background-color decoration, and since you cannot have gradient color in normal alert dialog, I used this.
code snippet
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: GestureDetector(
onTap: () { print("on tap title");},
child: Column(
children: <Widget>[
Container(
child: Image.asset('assets/images/background.jpg'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
),
content: GestureDetector(
onTap: () { print("on tap content");},
child: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
]
);
});
}
full code
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
class UnicornAlertDialog extends StatelessWidget {
const UnicornAlertDialog({
Key key,
#required this.gradient,
this.title,
this.titlePadding,
this.titleTextStyle,
this.content,
this.contentPadding = const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
this.contentTextStyle,
this.actions,
this.backgroundColor,
this.elevation,
this.semanticLabel,
this.shape,
}) : assert(contentPadding != null),
super(key: key);
final Gradient gradient;
final Widget title;
final EdgeInsetsGeometry titlePadding;
final TextStyle titleTextStyle;
final Widget content;
final EdgeInsetsGeometry contentPadding;
final TextStyle contentTextStyle;
final List<Widget> actions;
final Color backgroundColor;
final double elevation;
final String semanticLabel;
final ShapeBorder shape;
#override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = Theme.of(context);
final DialogTheme dialogTheme = DialogTheme.of(context);
final List<Widget> children = <Widget>[];
String label = semanticLabel;
if (title != null) {
children.add(Padding(
padding: titlePadding ?? EdgeInsets.fromLTRB(24.0, 24.0, 24.0, content == null ? 20.0 : 0.0),
child: DefaultTextStyle(
style: titleTextStyle ?? dialogTheme.titleTextStyle ?? theme.textTheme.title,
child: Semantics(
child: title,
namesRoute: true,
container: true,
),
),
));
} else {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
label = semanticLabel;
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
label = semanticLabel ?? MaterialLocalizations.of(context)?.alertDialogLabel;
}
}
if (content != null) {
children.add(Flexible(
child: Padding(
padding: contentPadding,
child: DefaultTextStyle(
style: contentTextStyle ?? dialogTheme.contentTextStyle ?? theme.textTheme.subhead,
child: content,
),
),
));
}
if (actions != null) {
children.add(ButtonTheme.bar(
child: ButtonBar(
children: actions,
),
));
}
Widget dialogChild = IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
if (label != null)
dialogChild = Semantics(
namesRoute: true,
label: label,
child: dialogChild,
);
return Dialog(
backgroundColor: backgroundColor,
gradient: gradient,
elevation: elevation,
shape: shape,
child: dialogChild,
);
}
}
class Dialog extends StatelessWidget {
const Dialog({
Key key,
this.gradient,
this.backgroundColor,
this.elevation,
this.insetAnimationDuration = const Duration(milliseconds: 100),
this.insetAnimationCurve = Curves.decelerate,
this.shape,
this.child,
}) : super(key: key);
final Color backgroundColor;
final double elevation;
final Duration insetAnimationDuration;
final Curve insetAnimationCurve;
final ShapeBorder shape;
final Widget child;
final Gradient gradient;
static const RoundedRectangleBorder _defaultDialogShape =
RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
static const double _defaultElevation = 24.0;
#override
Widget build(BuildContext context) {
final DialogTheme dialogTheme = DialogTheme.of(context);
return AnimatedPadding(
padding: MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
duration: insetAnimationDuration,
curve: insetAnimationCurve,
child: MediaQuery.removeViewInsets(
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
context: context,
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
child: Material(
color: backgroundColor ?? dialogTheme.backgroundColor ?? Theme.of(context).dialogBackgroundColor,
elevation: elevation ?? dialogTheme.elevation ?? _defaultElevation,
shape: shape ?? dialogTheme.shape ?? _defaultDialogShape,
type: MaterialType.card,
child: ClipRRect(
borderRadius: _defaultDialogShape.borderRadius,
child: Container(
decoration: BoxDecoration(
gradient: gradient
),
child: child,
),
),
),
),
),
),
);
}
}
_showDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return UnicornAlertDialog(
title: GestureDetector(
onTap: () { print("on tap title");},
child: Column(
children: <Widget>[
Container(
child: Image.asset('assets/images/background.jpg'),
),
const SizedBox(height: 15.0),
Container(
child: Text(
'Verify',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
)
],
),
),
content: GestureDetector(
onTap: () { print("on tap content");},
child: Text('You have successfully verified your mobile number',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15.0)),
),
gradient: LinearGradient(
colors: <Color>[
Color(0xDD4a00e0),
Color(0xFF8e2de2),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
actions: <Widget>[
]
);
});
}
Future<void> _ackAlert(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Not in stock'),
content: const Text('This item is no longer available'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
enum ConfirmAction { CANCEL, ACCEPT }
Future<ConfirmAction> _asyncConfirmDialog(BuildContext context) async {
return showDialog<ConfirmAction>(
context: context,
barrierDismissible: false, // user must tap button for close dialog!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Reset settings?'),
content: const Text(
'This will reset your device to its default factory settings.'),
actions: <Widget>[
FlatButton(
child: const Text('CANCEL'),
onPressed: () {
Navigator.of(context).pop(ConfirmAction.CANCEL);
},
),
FlatButton(
child: const Text('ACCEPT'),
onPressed: () {
Navigator.of(context).pop(ConfirmAction.ACCEPT);
},
)
],
);
},
);
}
Future<String> _asyncInputDialog(BuildContext context) async {
String teamName = '';
return showDialog<String>(
context: context,
barrierDismissible: false, // dialog is dismissible with a tap on the barrier
builder: (BuildContext context) {
return AlertDialog(
title: Text('Enter current team'),
content: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
autofocus: true,
decoration: new InputDecoration(
labelText: 'Team Name', hintText: 'eg. Juventus F.C.'),
onChanged: (value) {
teamName = value;
},
))
],
),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop(teamName);
},
),
],
);
},
);
}
enum Departments { Production, Research, Purchasing, Marketing, Accounting }
Future<Departments> _asyncSimpleDialog(BuildContext context) async {
return await showDialog<Departments>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return SimpleDialog(
title: const Text('Select Departments '),
children: <Widget>[
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Production);
},
child: const Text('Production'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Research);
},
child: const Text('Research'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Purchasing);
},
child: const Text('Purchasing'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Marketing);
},
child: const Text('Marketing'),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, Departments.Accounting);
},
child: const Text('Accounting'),
)
],
);
});
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: AppBar(
title: Text("Dialog"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
onPressed: () {
_showDialog(context);
},
child: const Text("Unicon Dialog"),
),
new RaisedButton(
onPressed: () {
_ackAlert(context);
},
child: const Text("Ack Dialog"),
),
new RaisedButton(
onPressed: () async {
final ConfirmAction action = await _asyncConfirmDialog(context);
print("Confirm Action $action" );
},
child: const Text("Confirm Dialog"),
),
new RaisedButton(
onPressed: () async {
final Departments deptName = await _asyncSimpleDialog(context);
print("Selected Departement is $deptName");
},
child: const Text("Simple dialog"),
),
new RaisedButton(
onPressed: () async {
final String currentTeam = await _asyncInputDialog(context);
print("Current team name is $currentTeam");
},
child: const Text("Input Dialog"),
),
],
),
),
);
}
}
void main() {
runApp(new MaterialApp(home: new MyApp()));
}

Categories

Resources