Related
what'd I miss ? is it because dart version or other things ,
environment:
sdk: ">=2.16.1 <3.0.0"
1. error
Error: The value 'null' can't be returned from a function with return
type 'Widget' because 'Widget' is not nullable.
'Widget' is from 'package:flutter/src/widgets/framework.dart'
// Alertdialog box showing
showAlertDialog(BuildContext context) {
AlertDialog alert = AlertDialog(
content: Padding(
padding: const EdgeInsets.only(top: 22.0, bottom: 22),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
child: Text(
"Would you like to get latest updates and notifications?",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 18),
),
),
SizedBox(height: 24),
Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
FlatButton(
onPressed: () {
setState(() {
snackBarText = "You will not recive notifications.";
});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"DENY",
style:
TextStyle(color: Colors.white, fontSize: 16, height: 1.2),
),
color: Colors.purple,
),
SizedBox(width: 10),
FlatButton(
onPressed: () {
setState(() {
snackBarText = "You will recive notifications.";
});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"ALLOW",
style: TextStyle(
color: Colors.purple, fontSize: 16, height: 1.2),
),
shape: RoundedRectangleBorder(
side: BorderSide(width: 1, color: Colors.purple)),
color: Colors.white,
)
])
],
),
),
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
**2.**error
lib/ua_Screens.dart:29:8: Error: Field '_image' should be initialized
because its type 'File' doesn't allow null.
'File' is from 'dart:io'. File _image;
^^^^^^
File _image;
Future get_image() async {
final image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_image = image;
});
}
I think you write wrong code, try below code hope its help to used. and one thing dont used FlatButton used TextButton because FlatButton is depriciated by flutter.
Refer TextButton
Your Alert Dialog function:
showAlertDialog(BuildContext context) {
return AlertDialog(
content: Padding(
padding: const EdgeInsets.only(top: 22.0, bottom: 22),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
child: Text(
"Would you like to get latest updates and notifications?",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 18),
),
),
SizedBox(height: 24),
Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
FlatButton(
onPressed: () {
setState(() {});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"DENY",
style:
TextStyle(color: Colors.white, fontSize: 16, height: 1.2),
),
color: Colors.purple,
),
SizedBox(width: 10),
FlatButton(
onPressed: () {
setState(() {});
Navigator.of(context).pop();
Navigator.of(context).pushReplacement(new MaterialPageRoute(
builder: (BuildContext context) => null));
},
child: Text(
"ALLOW",
style: TextStyle(
color: Colors.purple, fontSize: 16, height: 1.2),
),
shape: RoundedRectangleBorder(
side: BorderSide(width: 1, color: Colors.purple)),
color: Colors.white,
)
])
],
),
),
);
}
Your Widget:
ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return showAlertDialog(context);
},
);
},
child: Text('Pressed Me'),
),
Your result screen->
Your alert dialog->
Your Second error refer my answer here and here
This Error Showing When i Click On Notification Navigation Item from Profile Page To Notification
Exception has occurred. FlutterError (setState() called after
dispose(): _MyProfileState#c3ad1(lifecycle state: defunct, not
mounted) This error happens if you call setState() on a State object
for a widget that no longer appears in the widget tree (e.g., whose
parent widget no longer includes the widget in its build). This error
can occur when code calls setState() from a timer or an animation
callback. The preferred solution is to cancel the timer or stop
listening to the animation in the dispose() callback. Another solution
is to check the "mounted" property of this object before calling
setState() to ensure the object is still in the tree. This error might
indicate a memory leak if setState() is being called because another
object is retaining a reference to this State object after it has been
removed from the tree. To avoid memory leaks, consider breaking the
reference to this object during dispose().)
Profile Page :
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:play_big_win/constants.dart';
import 'package:play_big_win/services/firebase-auth-helper.dart';
class MyProfile extends StatefulWidget {
#override
_MyProfileState createState() => _MyProfileState();
}
class _MyProfileState extends State<MyProfile> {
final firebaseUser = FirebaseAuth.instance.currentUser;
final db = FirebaseFirestore.instance;
String fullname = '';
String email = '';
#override
void dispose() {
SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
super.dispose();
}
#override
initState() {
SystemChrome.setEnabledSystemUIOverlays([]);
super.initState();
}
getData() async {
while (mounted) {
dynamic names = await FirebaseAuthHelper().getCurrentUserData();
if (names != null) {
fullname = names[0];
email = names[1];
setState(() {});
} else {
print("Nulllll");
}
}
}
#override
Widget build(BuildContext context) {
getData();
return Scaffold(
backgroundColor: kPrimaryColor,
body: SafeArea(
child: ListView(
shrinkWrap: true,
children: [
SizedBox(
height: 20,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
width: MediaQuery.of(context).size.width - 25,
height: 150,
child: Row(
children: [
CircleAvatar(
radius: 60.0,
backgroundImage: NetworkImage(
'https://res.cloudinary.com/dqunmzmqo/image/upload/v1606248032/male-clipart-avatar_ewaerc.png',
),
),
Padding(
padding: const EdgeInsets.only(top: 45.0),
child: Column(
children: [
Text(
"Name: $fullname",
style: TextStyle(
fontSize: 14,
),
),
SizedBox(
height: 10,
),
Text(
"Email: $email",
style: TextStyle(
fontSize: 14,
),
),
SizedBox(
height: 10,
),
Text(
"Refer Code: Xasdsas",
style: TextStyle(
fontSize: 14,
),
)
],
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
'Play Big Win Big',
style: TextStyle(
fontFamily: 'Pacifico',
fontSize: 20.0,
color: Colors.white,
),
),
),
SizedBox(
height: 5,
),
Text(
'V1.0',
style: TextStyle(
fontSize: 10.0,
letterSpacing: 2.5,
color: Colors.teal.shade100,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 20.0,
width: 150.0,
child: Divider(
color: Colors.teal.shade100,
),
),
GestureDetector(
onTap: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => MyprivacyPolicy(),
// ));
},
child: Card(
color: Colors.white,
margin:
EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Icon(
Icons.group_add,
color: Colors.teal,
),
title: Text(
'Invite Friends',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17.0,
color: Colors.teal.shade900,
),
),
),
),
),
GestureDetector(
onTap: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => MyprivacyPolicy(),
// ));
},
child: Card(
color: Colors.white,
margin:
EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Icon(
Icons.question_answer,
color: Colors.teal,
),
title: Text(
"FAQ's",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17.0,
color: Colors.teal.shade900,
),
),
),
),
),
GestureDetector(
onTap: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => MyprivacyPolicy(),
// ));
},
child: Card(
color: Colors.white,
margin:
EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Icon(
Icons.privacy_tip,
color: Colors.teal,
),
title: Text(
'Privacy Policy',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17.0,
color: Colors.teal.shade900,
),
),
),
),
),
GestureDetector(
onTap: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => TermsandCondtions(),
// ));
},
child: Card(
color: Colors.white,
margin:
EdgeInsets.symmetric(vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Icon(
Icons.auto_fix_normal,
color: Colors.teal,
),
title: Text(
'Terms & Conditions',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17.0,
color: Colors.teal.shade900,
),
),
),
),
),
],
),
],
),
),
);
}
}
Notification Page:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../constants.dart';
class MyNotification extends StatefulWidget {
#override
_MyNotificationState createState() => _MyNotificationState();
}
class _MyNotificationState extends State<MyNotification> {
#override
void dispose() {
SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
super.dispose();
}
#override
initState() {
SystemChrome.setEnabledSystemUIOverlays([]);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: kPrimaryColor,
title: Text(
"Notifications",
),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Container(
decoration: BoxDecoration(
color: Colors.deepPurple,
borderRadius: BorderRadius.all(
Radius.circular(
20,
),
),
),
height: 300,
width: MediaQuery.of(context).size.width,
child: Center(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
"Today Is Your sadsadasdas das das dsa sa dsa dsad asd as das asd sad asd asds das sa dsa",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
),
),
),
),
),
);
}
}
My Authenticate Code:
Future getCurrentUserData() async {
try {
DocumentSnapshot ds = await users.doc(firebaseUser.uid).get();
String fullname = ds.get('full_name');
String email = ds.get('email');
return [fullname, email];
} catch (e) {
print(e.toString());
return null;
}
}
This Code Which I Call in Profile Page:
getData() async {
while (mounted) {
dynamic names = await FirebaseAuthHelper().getCurrentUserData();
if (names != null) {
fullname = names[0];
email = names[1];
setState(() {});
} else {
print("Null");
}
}
}
You are using setState in async function, After an await, your widget may not be mounted anymore. Doing setState gives you an exception at that time. use the below code or place it at any other place
if (this.mounted) {
setState(() {
});
}
or more clear approach override setState
#override
void setState(fn) {
if(mounted) {
super.setState(fn);
}
}
I am still a novice with flutter and I am working on a quiz app right now
In the radio button list whenever the app goes to next question the radio buttons are not getting reset and I will be grateful if someone can guide me on how I can reset radio button on calling next question function
Pseudocode
class _QuizPageState extends State<QuizPage> {
List<dynamic> myQuestion;
_QuizPageState(this.myQuestion);
int i = 0;
int count = 0;
int selectedRadioTile;
int marks = 0;
var selected;
Widget choiceButton(String k, int value) {
return Padding(
padding: EdgeInsets.symmetric(
vertical: 10,
),
child: RadioListTile(
value: value,
groupValue: selectedRadioTile,
title: Container(
child: Text(myQuestion[i][k] ?? "None"),
),
onChanged: (val) {
setSelectedRadioTile(val);
selected = val;
},
activeColor: Colors.green,
selected: true,
),
);
}
void initState() {
selectedRadioTile = 0;
super.initState();
}
setSelectedRadioTile(int val) {
setState(() {
selectedRadioTile = val;
});
}
void checkAnswer() {
var e = int.parse(myQuestion[i]["Answer"]);
if (e == selected) {
marks = marks + 1;
} else {
print("wrong");
}
nextquestion();
}
void nextquestion() {
setState(() {
if (count < 9) {
i = randomBetween(0, myQuestion.length);
} else {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => resultpage(marks: marks),
));
}
});
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Alert",
),
content: Text("You Can't Go Back At This Stage."),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Ok',
),
)
],
));
},
child: Scaffold(
appBar: AppBar(
elevation: 30.0,
title: Center(
child: Text(
'Quiz',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontFamily: "Quando",
fontWeight: FontWeight.bold,
),
),
),
backgroundColor: Colors.amber[800],
),
body: LayoutBuilder(
builder: (context, constraint) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraint.maxHeight),
child: IntrinsicHeight(
child: Column(
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Center(
child: Container(
padding: EdgeInsets.only(top: 20, left: 10),
child: Text(
myQuestion[i]["Question"] ?? "None",
style: TextStyle(
fontSize: 15.0,
fontFamily: "Quando",
fontWeight: FontWeight.bold,
),
),
),
),
SizedBox(
height: 20,
),
Expanded(
child: AspectRatio(
aspectRatio: 16 / 11,
child: ClipRect(
child: SizedBox(
height: 50,
child: PhotoView(
imageProvider: AssetImage(
myQuestion[i]["Image"] ?? "None"),
minScale:
PhotoViewComputedScale.contained *
0.5,
maxScale:
PhotoViewComputedScale.covered * 2,
initialScale: 0.6,
backgroundDecoration: BoxDecoration(
color: Theme.of(context).canvasColor,
),
),
),
),
),
),
Text(
"To adjust the image double Tap",
style: TextStyle(
fontFamily: "Quando",
color: Colors.black26,
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
],
),
),
SizedBox(
height: 10,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
choiceButton("option1", 1),
choiceButton("option2", 2),
choiceButton("option3", 3),
choiceButton("option4", 4),
],
),
),
Expanded(
flex: 0,
child: RaisedButton(
splashColor: Colors.blueAccent,
color: Colors.blueAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
onPressed: () {
checkAnswer();
count = count + 1;
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Explaination",
),
content: Text(
myQuestion[i]["Explanation"] ?? "None",
style: TextStyle(
fontSize: 15.0,
fontFamily: "Quando",
),
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Ok',
),
)
],
));
},
child: Text(
'Submit',
),
),
),
SizedBox(
height: 40,
)
],
),
),
),
);
},
),
),
);
}
}
You could just set selectedRadioTile to 0 in nextQuestion:
void nextquestion() {
setState(() {
selectedRadioTile = 0;
if (count < 9) {
i = randomBetween(0, myQuestion.length);
} else {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => resultpage(marks: marks),
));
}
});
}
This is my dialog Code
Here is am getting an error of setstate() or MarkerneedsBuild called during the build. this overlay widget cannot be marked as needing to process of building widgets.
When I am trying to call _onAlertOtp widget it will show me this error.in the build method, i've bloc and state when my signup is successful then i have to call alert dialog. but when I am trying to do that it will show me the error. Hope you understand the question please help me.
_onAlertotp(BuildContext context) {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Enter OTP'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height / 2.7,
width: MediaQuery.of(context).size.width,
alignment: Alignment.center,
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'We have Texted and/or Emailed OTP (One Time Pin) to your registered cell phone and/ or email account. Please check and enter OTP below to activate your TUDO account.',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 15),
textAlign: TextAlign.center,
),
),
SizedBox(
height: 5,
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0, horizontal: 30),
child: PinCodeTextField(
length: 6, // must be greater than 0
obsecureText: false, //optional, default is false
shape: PinCodeFieldShape
.underline, //optional, default is underline
onDone: (String value) {
setState(() {
passcode = value;
print(value);
});
},
textStyle: TextStyle(
fontWeight: FontWeight
.bold), //optinal, default is TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)
onErrorCheck: (bool value) {
setState(() {
hasError = value;
});
},
shouldTriggerFucntions:
changeNotifier.stream.asBroadcastStream(),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30.0),
child: Text(
hasError
? "*Please fill up all the cells and press VERIFY again"
: "",
style: TextStyle(
color: Colors.red.shade300, fontSize: 12),
),
),
SizedBox(
height: 20,
),
RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: "Didn't receive the code? ",
style:
TextStyle(color: Colors.black54, fontSize: 15),
children: [
TextSpan(
text: " RESEND",
// recognizer: onTapRecognizer,
style: TextStyle(
color: colorStyles["primary"],
fontWeight: FontWeight.bold,
fontSize: 16))
]),
),
SizedBox(
height: 7,
),
Container(
margin: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 30),
child: ButtonTheme(
height: 50,
child: FlatButton(
onPressed: () async {
/// check the [_onData] fucntion to understand better
changeNotifier.add(Functions.submit);
// at first we will check error on the press of the button.
if (!hasError) {
_onAlertrunnigbusiness(context);
}
},
child: Center(
child: Text(
"VERIFY".toUpperCase(),
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold),
)),
),
),
decoration: BoxDecoration(
color: colorStyles["primary"],
borderRadius: BorderRadius.circular(5),
),
),
],
),
),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Regret'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Here Is Another DIalog. which open on first dialog verify button click
_onAlertrunnigbusiness(context) {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Are you running Business?'),
content: Container(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
height: 10,
),
Text(
"TUDO.App aims at Businesses bridging gaps between Business Service Providers and Consumers collaborate on unique technology platform. If you own a business, we strongly recommend, provide your business information to grow your customer base and expand your business services. Any questions? Call us #1-800-888-TUDO"),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FlatButton.icon(
icon: Icon(FontAwesomeIcons.arrowCircleRight),
label: Text('No'),
color: colorStyles["primary"],
textColor: Colors.white,
padding:
EdgeInsets.symmetric(vertical: 10, horizontal: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () {
NavigationHelper.navigatetoMainscreen(context);
},
),
SizedBox(height: 10),
FlatButton.icon(
icon: Icon(FontAwesomeIcons.arrowCircleRight),
label: Text('Yes'),
color: colorStyles["primary"],
textColor: Colors.white,
padding:
EdgeInsets.symmetric(vertical: 10, horizontal: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(7),
),
onPressed: () {
NavigationHelper.navigatetoBspsignupcreen(context);
},
),
],
)
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
And Here i am calling my dialog
#override
Widget build(BuildContext context) {
return BlocListener<SignupBloc, SignupState>(
bloc: widget._signupBloc,
listener: (
BuildContext context,
SignupState currentState,
) {
if (currentState is InSignupState) {
_countries = currentState.countries.countries;
return Container(child: content(_signupBloc, context, _countries));
}
if (currentState is SignupButtonClickedEvent) {
print('SignupButtonClickedEvent clicked');
return Container();
}
if (currentState is SignupSuccessState) {
print(
' You are awesome. you have successfully registered without confirmation');
print(currentState.signupUser.toJson());
print("Hey Otp Is opned");
if (!_isError) {
return _onAlertotp(context);
}
// NavigationHelper.navigatetoMainscreen(context);
_isLoading = false;
showAlertBox = true;
return Container(
child: content(_signupBloc, context, _countries),
);
}
if (currentState is SignupVerficationOtp) {
print('signup verficitaion otp button clicked');
return Container();
}
return Container(child: content(_signupBloc, context, _countries));
},
);
}
}
try using below code to display an alert dialog
in place of return _onAlertotp(context);
WidgetsBinding.instance.addPostFrameCallback((_) {
// show alert dialog here
_onAlertotp(context);
});
You should use a BlocListener at the root of your build method to handle events that do not return a widget (in your case the showDialog method)
Your if (currentState is SignupSuccessState) { part would be in the BlocListener and not in the BlocBuilder
I'm new to flutter and need to create a gallery app that needs a custom dialog box to show the selected image. How can I implement that?
Use Dialog class which is a parent class to AlertDialog class in Flutter. Dialog widget has a argument , "shape" which you can use to shape the Edges of the Dialog box.
Here is a code sample:
Dialog errorDialog = Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), //this right here
child: Container(
height: 300.0,
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.all(15.0),
child: Text('Cool', style: TextStyle(color: Colors.red),),
),
Padding(
padding: EdgeInsets.all(15.0),
child: Text('Awesome', style: TextStyle(color: Colors.red),),
),
Padding(padding: EdgeInsets.only(top: 50.0)),
TextButton(onPressed: () {
Navigator.of(context).pop();
},
child: Text('Got It!', style: TextStyle(color: Colors.purple, fontSize: 18.0),))
],
),
),
);
showDialog(context: context, builder: (BuildContext context) => errorDialog);}
Screenshot (Null Safe):
Code:
Just call this method:
void showCustomDialog(BuildContext context) {
showGeneralDialog(
context: context,
barrierLabel: "Barrier",
barrierDismissible: true,
barrierColor: Colors.black.withOpacity(0.5),
transitionDuration: Duration(milliseconds: 700),
pageBuilder: (_, __, ___) {
return Center(
child: Container(
height: 240,
child: SizedBox.expand(child: FlutterLogo()),
margin: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(40)),
),
);
},
transitionBuilder: (_, anim, __, child) {
Tween<Offset> tween;
if (anim.status == AnimationStatus.reverse) {
tween = Tween(begin: Offset(-1, 0), end: Offset.zero);
} else {
tween = Tween(begin: Offset(1, 0), end: Offset.zero);
}
return SlideTransition(
position: tween.animate(anim),
child: FadeTransition(
opacity: anim,
child: child,
),
);
},
);
}
On a button click show dialog as -
showDialog(
context: context,
builder: (_) => LogoutOverlay(),
);
Dialog design with two buttons -
class LogoutOverlay extends StatefulWidget {
#override
State<StatefulWidget> createState() => LogoutOverlayState();
}
class LogoutOverlayState extends State<LogoutOverlay>
with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> scaleAnimation;
#override
void initState() {
super.initState();
controller =
AnimationController(vsync: this, duration: Duration(milliseconds: 450));
scaleAnimation =
CurvedAnimation(parent: controller, curve: Curves.elasticInOut);
controller.addListener(() {
setState(() {});
});
controller.forward();
}
#override
Widget build(BuildContext context) {
return Center(
child: Material(
color: Colors.transparent,
child: ScaleTransition(
scale: scaleAnimation,
child: Container(
margin: EdgeInsets.all(20.0),
padding: EdgeInsets.all(15.0),
height: 180.0,
decoration: ShapeDecoration(
color: Color.fromRGBO(41, 167, 77, 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0))),
child: Column(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.only(
top: 30.0, left: 20.0, right: 20.0),
child: Text(
"Are you sure, you want to logout?",
style: TextStyle(color: Colors.white, fontSize: 16.0),
),
)),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: ButtonTheme(
height: 35.0,
minWidth: 110.0,
child: RaisedButton(
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0)),
splashColor: Colors.white.withAlpha(40),
child: Text(
'Logout',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 13.0),
),
onPressed: () {
setState(() {
Route route = MaterialPageRoute(
builder: (context) => LoginScreen());
Navigator.pushReplacement(context, route);
});
},
)),
),
Padding(
padding: const EdgeInsets.only(
left: 20.0, right: 10.0, top: 10.0, bottom: 10.0),
child: ButtonTheme(
height: 35.0,
minWidth: 110.0,
child: RaisedButton(
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0)),
splashColor: Colors.white.withAlpha(40),
child: Text(
'Cancel',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 13.0),
),
onPressed: () {
setState(() {
/* Route route = MaterialPageRoute(
builder: (context) => LoginScreen());
Navigator.pushReplacement(context, route);
*/ });
},
))
),
],
))
],
)),
),
),
);
}
}
You just put this class in your project and call its method for showing dialog. Using this class you don't need to write dialog code everywhere
class DialogUtils {
static DialogUtils _instance = new DialogUtils.internal();
DialogUtils.internal();
factory DialogUtils() => _instance;
static void showCustomDialog(BuildContext context,
{#required String title,
String okBtnText = "Ok",
String cancelBtnText = "Cancel",
#required Function okBtnFunction}) {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text(title),
content: /* Here add your custom widget */,
actions: <Widget>[
FlatButton(
child: Text(okBtnText),
onPressed: okBtnFunction,
),
FlatButton(
child: Text(cancelBtnText),
onPressed: () => Navigator.pop(context))
],
);
});
}
}
You can call this method like :
GestureDetector(
onTap: () =>
DialogUtils.showCustomDialog(context,
title: "Gallary",
okBtnText: "Save",
cancelBtnText: "Cancel",
okBtnFunction: () => /* call method in which you have write your logic and save process */),
child: Container(),
)
Alert Dialog
Custom Dialog
Full-Screen Dialog
ref: Flutter Alert Dialog to Custom Dialog | by Ishan Fernando | CodeChai | Medium
Alert Dialog
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Alert Dialog"),
content: Text("Dialog Content"),
actions: [
TextButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
Custom Dialog
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0)), //this right here
child: Container(
height: 200,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'What do you want to remember?'),
),
SizedBox(
width: 320.0,
child: RaisedButton(
onPressed: () {},
child: Text(
"Save",
style: TextStyle(color: Colors.white),
),
color: const Color(0xFF1BC0C5),
),
)
],
),
),
),
);
});
Full-Screen Dialog
showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: MaterialLocalizations.of(context)
.modalBarrierDismissLabel,
barrierColor: Colors.black45,
transitionDuration: const Duration(milliseconds: 200),
pageBuilder: (BuildContext buildContext,
Animation animation,
Animation secondaryAnimation) {
return Center(
child: Container(
width: MediaQuery.of(context).size.width - 10,
height: MediaQuery.of(context).size.height - 80,
padding: EdgeInsets.all(20),
color: Colors.white,
child: Column(
children: [
RaisedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Save",
style: TextStyle(color: Colors.white),
),
color: const Color(0xFF1BC0C5),
)
],
),
),
);
});
An General E.g
showDialog(context: context,builder: (context) => _onTapImage(context)); // Call the Dialog.
_onTapImage(BuildContext context) {
return Stack(
alignment: Alignment.center,
children: <Widget>[
Image.network('https://via.placeholder.com/150',fit: BoxFit.contain,), // Show your Image
Align(
alignment: Alignment.topRight,
child: RaisedButton.icon(
color: Theme.of(context).accentColor,
textColor: Colors.white,
onPressed: () => Navigator.pop(context),
icon: Icon(
Icons.close,
color: Colors.white,
),
label: Text('Close')),
),
],
);
}
I usually build a wrapper for the dialog that matches the app theme and avoids much redundant code.
PlaceholderDialog
class PlaceholderDialog extends StatelessWidget {
const PlaceholderDialog({
this.icon,
this.title,
this.message,
this.actions = const [],
Key? key,
}) : super(key: key);
final Widget? icon;
final String? title;
final String? message;
final List<Widget> actions;
#override
Widget build(BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
icon: icon,
title: title == null
? null
: Text(
title!,
textAlign: TextAlign.center,
),
titleTextStyle: AppStyle.bodyBlack,
content: message == null
? null
: Text(
message!,
textAlign: TextAlign.center,
),
contentTextStyle: AppStyle.textBlack,
actionsAlignment: MainAxisAlignment.center,
actionsOverflowButtonSpacing: 8.0,
actions: actions,
);
}
}
Usage
showDialog(
context: context,
builder: (ctx) => PlaceholderDialog(
icon: Icon(
Icons.add_circle,
color: Colors.teal,
size: 80.0,
),
title: 'Save Failed',
message: 'An error occurred when attempt to save the message',
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: Text('!Got It'),
),
],
),
);
Result
You can now use AlertDialog and in content build your widget.
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
backgroundColor: Colors.green,
content: Container(
height:200,
width:200,
decoration: BoxDecoration(
image: DecorationImage(
image: FileImage(filepath),
fit: BoxFit.cover))),}),
There's a working solution in my case:
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('AlertDialog Title'),
content: SingleChildScrollView(
child: Column(
children: <Widget>[
Text('This is a demo alert dialog.'),
Text('Would you like to confirm this message?'),
],
),
),
actions: <Widget>[
TextButton(
child: Text('Confirm'),
onPressed: () {
print('Confirmed');
Navigator.of(context).pop();
},
),
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Hope this is helpful:
I've made static function in a separate class:
import 'package:flutter/material.dart';
import 'package:flutter_application_1/TGColors.dart';
class TGDialog
{
static doNothing() { } // stub needed for Function parameters
/// Returns an AlertDialog with most optional parameters
static AlertDialog dlg( BuildContext context,
{ String txtTitle = 'WHAT? no title?' ,
String txtMsg = 'WHAT? no content?',
String txtBtn1 = 'CANCEL' ,
String txtBtn2 = 'OK' ,
Function funcBtn1 = doNothing ,
Function funcBtn2 = doNothing ,
Color colBackground = TGColors.Orange ,
Color colText = TGColors.Indigo } )
{
return
AlertDialog(
backgroundColor : colBackground,
title : Text(txtTitle),
content : Text(txtMsg),
actions : <Widget>
[
TextButton(
onPressed : () => { funcBtn1(), Navigator.pop(context,'Cancel')},
child : Text(txtBtn1, style: TextStyle(color: colText)),
),
TextButton(
onPressed :() => { funcBtn2(),Navigator.pop(context) },
child : Text(txtBtn2, style: TextStyle(color: colText)),
),
],
);
}
}
An example:
Positioned( bottom: 1, left: (screenW / 5.6),
child : FloatingActionButton(
heroTag : 'clear',
onPressed :() => showDialog<String>
(
context : context,
builder : (BuildContext context) =>
///////////////////////////////////////////////////////
TGDialog.dlg( context,
txtTitle : 'Clear Order?',
txtMsg : 'This resets all item counts' ,
funcBtn2 : resetOrder)
///////////////////////////////////////////////////////
),
child : const Text('clear\nall', textAlign: TextAlign.center),
shape : RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40),
),
),
),
etc.
Btw: I like CSS webcolors so I defined them in a separate class
like so:
import 'dart:ui';
/// Contains mainly web colors (based on CSS)
///
/// Usage e.g: ... = TGcolors.CornFlowerBlue
class TGColors
{
static const PrimaryColor = Color(0xFF808080);
static const AliceBlue = Color(0xFFF0F8FF);
static const AntiqueWhite = Color(0xFFFAEBD7);
static const Aqua = Color(0xFF00FFFF);
static const Aquamarine = Color(0xFF7FFFD4);
// etc.
Custom Alert Dialog in Flutter
void openAlert() {
dialog = Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0)),
//this right here
child: Container(
height: 350.0,
width: double.infinity,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ClipRRect(
child: Image.asset(
"assets/images/water1.jpg",
width: double.infinity,
height: 180,
fit: BoxFit.cover,
),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16), topRight: Radius.circular(16)),
),
Container(
margin: EdgeInsets.only(top: 16),
decoration: boxDecorationStylealert,
width: 200,
padding: EdgeInsets.symmetric(horizontal: 8),
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
showToastMessage("-");
},
child:Image.asset("assets/images/subtraction.png",width: 30,height: 30,)),
Text(
"1",
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.bold,
color: black_color),
),
GestureDetector(
onTap: () {
showToastMessage("+");
},
child:Image.asset("assets/images/add.png",width: 30,height: 30,)),
],
),
),
Expanded(child: Container()),
Row(
children: [
Expanded(
child: Padding(
padding: EdgeInsets.only(left: 12, right: 6),
child: MaterialButton(
onPressed: cancelClick,
color: green_color,
child: Text(
"CANCEL",
style: TextStyle(fontSize: 12, color: white_color),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(left: 6, right: 12),
child: MaterialButton(
onPressed: okClick,
color: green_color,
child: Text(
"OK",
style: TextStyle(fontSize: 12, color: white_color),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
),
),
)
],
)
],
),
),
);
showDialog(
context: context, builder: (BuildContext context) => dialog);
}