Flutter ProgressDialog hidden - flutter

I have developed a Flutter application and I used ProgressDialog widget (progress_dialog: ^1.2.0). First, I show the ProgressDialog widget and after some code, then I try to hide ProgressDialog. But it doesn't work.
This is my code
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
#override
Widget build(BuildContext context) {
pr = new ProgressDialog(context,type: ProgressDialogType.Normal);
pr.style(
message: 'Sing Up .......',
borderRadius: 20.0,
backgroundColor: Colors.white,
progressWidget: CircularProgressIndicator(),
maxProgress: 1.0,
);
return Scaffold(
backgroundColor: Color.fromRGBO(23, 63, 73, 1),
appBar: AppBar(
title: Text("Sign up"),
backgroundColor: Colors.black,
),body: Stack(
......
_addUser();
),
);
}
Future _addUser() async {
pr.show();
.........
pr.hide();
}
}
After that, I find the solution to this problem.
Future.delayed(Duration(seconds: 3)).then((value) {
pr.hide();
});
But why does ProgressDialog.hide() not work here but it works after delaying the process??

When your code execute to pr.hide() the progress_dialog still not show on screen
so your pr.hide() not work
you can see issues https://github.com/fayaz07/progress_dialog/issues/38
and check pr.isShowing() will not work because in source code of progress_dialog https://github.com/fayaz07/progress_dialog/blob/master/lib/progress_dialog.dart
bool _isShowing is ahead before real showDialog()
code snippet of progress_dialog
void show() {
if (!_isShowing) {
_dialog = new _Body();
_isShowing = true;
if (_showLogs) debugPrint('ProgressDialog shown');
showDialog<dynamic>(
context: _context,
barrierDismissible: false,
builder: (BuildContext context) {
_dismissingContext = context;
return WillPopScope(
onWillPop: () {
return Future.value(_barrierDismissible);
},
child: Dialog(
backgroundColor: _backgroundColor,
insetAnimationCurve: _insetAnimCurve,
insetAnimationDuration: Duration(milliseconds: 100),
elevation: _dialogElevation,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(_borderRadius))),
child: _dialog),
);
},
);
} else {
if (_showLogs) debugPrint("ProgressDialog already shown/showing");
}
}
}
full test code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:progress_dialog/progress_dialog.dart';
ProgressDialog pr;
void main() {
runApp(MaterialApp(
home: FirstScreen(),
));
}
class MyApp extends StatelessWidget {
double percentage = 0.0;
#override
Widget build(BuildContext context) {
// pr = new ProgressDialog(context,
// type: ProgressDialogType.Normal, isDismissible: false);
pr = new ProgressDialog(context, type: ProgressDialogType.Download);
pr.style(
message: 'Downloading file...',
borderRadius: 10.0,
backgroundColor: Colors.white,
elevation: 10.0,
insetAnimCurve: Curves.easeInOut,
progress: 0.0,
maxProgress: 100.0,
progressTextStyle: TextStyle(
color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.w400),
messageTextStyle: TextStyle(
color: Colors.black, fontSize: 19.0, fontWeight: FontWeight.w600),
);
return Scaffold(
body: Center(
child: RaisedButton(
child: Text(
'Show Dialog',
style: TextStyle(color: Colors.white),
),
color: Colors.blue,
onPressed: () {
pr.show();
Future.delayed(Duration(seconds: 2)).then((onvalue) {
percentage = percentage + 30.0;
print(percentage);
pr.update(
progress: percentage,
message: "Please wait...",
progressWidget: Container(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator()),
maxProgress: 100.0,
progressTextStyle: TextStyle(
color: Colors.black,
fontSize: 13.0,
fontWeight: FontWeight.w400),
messageTextStyle: TextStyle(
color: Colors.black,
fontSize: 19.0,
fontWeight: FontWeight.w600),
);
Future.delayed(Duration(seconds: 2)).then((value) {
percentage = percentage + 30.0;
pr.update(
progress: percentage, message: "Few more seconds...");
print(percentage);
Future.delayed(Duration(seconds: 2)).then((value) {
percentage = percentage + 30.0;
pr.update(progress: percentage, message: "Almost done...");
print(percentage);
Future.delayed(Duration(seconds: 2)).then((value) {
pr.hide().whenComplete(() {
print(pr.isShowing());
});
percentage = 0.0;
});
});
});
});
Future.delayed(Duration(seconds: 10)).then((onValue) {
print("PR status ${pr.isShowing()}");
if (pr.isShowing())
pr.hide().then((isHidden) {
print(isHidden);
});
print("PR status ${pr.isShowing()}");
});
}),
),
);
}
}
class FirstScreen extends StatefulWidget {
#override
_FirstScreenState createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
ProgressDialog pr;
#override
Widget build(BuildContext context) {
pr = new ProgressDialog(context, showLogs: true);
pr.style(message: 'Please wait...');
return Scaffold(
body: Center(
child: RaisedButton(
child: Text('Show dialog and go to next screen',
style: TextStyle(color: Colors.white)),
color: Colors.blueAccent,
onPressed: () async{
print("before pr show");
pr.show();
print("after pr show");
print(pr.isShowing());
pr.hide().whenComplete((){print("hide complete");}
);
print("after pr hide");
print(pr.isShowing());
/*Future.delayed(Duration(seconds: 3)).then((value) {
pr.hide().whenComplete(() {
Navigator.of(context).push(CupertinoPageRoute(
builder: (BuildContext context) => SecondScreen()));
});
});*/
},
),
),
);
}
}
class SecondScreen extends StatefulWidget {
#override
_SecondScreenState createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('I am second screen')),
);
}
}

Related

PopupMenuButton not able to change icon when clicked

I'm using the PopupMenuButton in flutter for a web based project and trying to change the popupmenubutton icon when it's clicked. So in its initial state it would show Icons.menu and when opened, it could would Icons.close and once clicked again revert back to Icons.menu.
I have tried onSelected which does not get called at all when clicked in an attempt to change the icon.
I have used an icon or a child IconButton per the docs and used onPressed to setState however that doesn't work either.
Currently the elevated button when clicked, does not show the dropdown menu, nor does it update the icon.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool menuClicked = true;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
PointerInterceptor(
intercepting: true,
child: PopupMenuButton<String>(
offset: const Offset(10.0, 50.0),
color: Colors.black,
child: ElevatedButton(
onPressed: () {
setState(() {
menuClicked = !menuClicked;
});
},
child: Icon((menuClicked = true)
? Icons.menu
: Icons.close),),
itemBuilder: (BuildContext context) =>
<PopupMenuEntry<String>>[
PopupMenuItem(
value: "close",
child: ListTile(
leading: Icon(Icons.close, color: Colors.white),
title: Text('Close',
style: TextStyle(color: Colors.white)),
onTap: () {
Navigator.pop(context);
}),
),
],
),
],
),
),
body: Center(
child: Text('test'),
),
);
}
}
Equal sign will be ==
Icon((menuClicked == true) ? Icons.menu : Icons.close),
or you can do
Icon(menuClicked ? Icons.menu : Icons.close),
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool menuClicked = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
onPanDown: (details) {
setState(() {
menuClicked = true;
});
},
child: PopupMenuButton<String>(
offset: const Offset(10.0, 50.0),
color: Colors.black,
onSelected: (value) {
setState(() {
menuClicked = false;
});
},
padding: EdgeInsets.zero,
onCanceled: () {
setState(() {
menuClicked = false;
});
},
child: Icon(menuClicked ? Icons.close : Icons.menu),
itemBuilder: (BuildContext context) => [
PopupMenuItem(
value: "close",
child: ListTile(
leading: Icon(Icons.close, color: Colors.white),
title: Text(
'Close',
style: TextStyle(color: Colors.white),
),
onTap: () {
Navigator.pop(context);
},
),
),
],
),
),
],
),
);
}
}

How to use google login in flutter and bypass emailverification

I am new to Flutter, I am currently using a logic i got from youtube to verify email first before logging in the app. The logic works just fine but now I want to make use of Google Login as an alternative.
First issue is, email address always returns null when i use google login. And i couldn't access the FirebaseAuth.instance.currentUser!.emailVerified when googleLogIn is used.
Secondly, there is no need for email verification again when using google to sign in to the app.
the App logic goes here:
Main App Page
class MyApp extends StatelessWidget {
const MyApp({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
scaffoldMessengerKey: Utils.messengerKey,
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
home: const AuthWrapper(),
);
}
}
class AuthWrapper extends StatelessWidget {
const AuthWrapper({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return const Center(
child: Text('Something went wrong'),
);
}
if (snapshot.hasData) {
return const VerifyEmailPage();
} else {
return const AuthPage();
}
}),
);
}
}
VerifyEmailPage
class VerifyEmailPage extends StatefulWidget {
const VerifyEmailPage({Key? key}) : super(key: key);
#override
State<VerifyEmailPage> createState() => _VerifyEmailPageState();
}
class _VerifyEmailPageState extends State<VerifyEmailPage> {
bool isEmailVerified = false;
bool canResendEmail = false;
Timer? timer;
get label => null;
#override
void initState() {
super.initState();
//user needs to be created before
isEmailVerified = FirebaseAuth.instance.currentUser!.emailVerified;
if (!isEmailVerified) {
sendVerificationEmail();
timer = Timer.periodic(
const Duration(seconds: 10),
(_) => checkEmailVerified(),
);
}
}
#override
void dispose() {
timer?.cancel();
super.dispose();
}
Future checkEmailVerified() async {
//call after email verification
await FirebaseAuth.instance.currentUser!.reload();
setState(() {
isEmailVerified = FirebaseAuth.instance.currentUser!.emailVerified;
});
if (isEmailVerified) timer?.cancel();
}
Future sendVerificationEmail() async {
try {
final user = FirebaseAuth.instance.currentUser!;
await user.sendEmailVerification();
setState(() => canResendEmail = false);
await Future.delayed(const Duration(seconds: 5));
setState(() => canResendEmail = true);
} catch (e) {
Utils.showSnackBar(e.toString());
}
}
#override
Widget build(BuildContext context) {
return isEmailVerified
? const HomeScreen()
: Scaffold(
appBar: AppBar(
backgroundColor: lightblue,
centerTitle: true,
elevation: 0,
title: const Text(
'Verify Email',
),
),
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: backgroundgradient,
),
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'A verification email has been sent to your email',
style: TextStyle(fontSize: 18, color: Colors.white),
textAlign: TextAlign.center,
),
const SizedBox(
height: 20,
),
ElevatedButton.icon(
label: const Text('Resent Email'),
icon: const Icon(
Icons.email,
size: 32,
),
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(50)),
onPressed:
canResendEmail ? sendVerificationEmail : null,
),
const SizedBox(
height: 8,
),
TextButton(
onPressed: () => FirebaseAuth.instance.signOut(),
child: const Text(
'Cancel',
style: TextStyle(fontSize: 14, color: Colors.white38),
),
)
],
),
),
),
));
}
}
Lastly my Google Login Button
Widget _googleSignInButton() {
return OutlinedButton.icon(
icon: Image.asset(
'assets/google_logo.png',
scale: 25,
),
label: const Text('Sign in with Google'),
onPressed: () async {
final newUser = await _googleSignIn.signIn();
final googleAuth = await newUser!.authentication;
final creds = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
await FirebaseAuth.instance.signInWithCredential(creds);
},
style: OutlinedButton.styleFrom(
minimumSize: const Size.fromHeight(50),
padding: const EdgeInsets.all(15),
elevation: 1,
primary: Colors.white54,
side: const BorderSide(
color: Colors.white30,
),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
),
);
}
}
I'd really appreciate an alternative or an easy work around to solve this.
Thank you in anticipation.

error with speech to text in flutter while buiding for web

I am trying to build a speech to text app in flutter(using dart) . I get this error when I run however there are no issues with the code as far as I can tell. I've pasted the entire code below.
The error I am getting is when the onListen Handler is called. It points to an error in the speech to text package which isn't even my code. pls see image and error below.
TypeError: result[$item] is not a function
at speech_to_text_web.SpeechToTextPlugin.new.[_onResult] (http://localhost:53227/packages/speech_to_text/speech_to_text_web.dart.lib.js:143:36)
at http://localhost:53227/packages/speech_to_text/speech_to_text_web.dart.lib.js:97:98
at Object._checkAndCall (http://localhost:53227/dart_sdk.js:5242:16)
at Object.dcall (http://localhost:53227/dart_sdk.js:5247:17)
at SpeechRecognition.<anonymous> (http://localhost:53227/dart_sdk.js:100617:100)
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import 'package:avatar_glow/avatar_glow.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter voice',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.red,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SpeechScreen(),
);
}
}
class SpeechScreen extends StatefulWidget {
#override
_SpeechScreenState createState() => _SpeechScreenState();
}
class _SpeechScreenState extends State<SpeechScreen> {
stt.SpeechToText _speech = stt.SpeechToText();
bool _isListening = false;
String _text = 'Press the button and start speaking';
double _confidence = 1.0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Confidence: ${(_confidence * 100.0).toStringAsFixed(1)}%'),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: AvatarGlow(
animate: _isListening,
glowColor: Theme.of(context).primaryColor,
endRadius: 75.0,
duration: const Duration(milliseconds: 2000),
repeatPauseDuration: const Duration(milliseconds: 100),
repeat: true,
child: FloatingActionButton(
onPressed: _listen,
child: Icon(_isListening ? Icons.mic : Icons.mic_none),
),
),
body: SingleChildScrollView(
reverse: true,
child: Container(
padding: const EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 150.0),
child: Text(
_text,
style: const TextStyle(
fontSize: 32.0,
color: Colors.black,
fontWeight: FontWeight.w400,
),
),
),
),
);
}
void _listen() async {
if (!_isListening) {
bool available = await _speech.initialize(
onStatus: (val) => print('onStatus: $val'),
onError: (val) => print('onError: $val'),
);
if (available) {
setState(() => _isListening = true);
_speech.listen(
onResult: (val) => setState(() {
_text = val.recognizedWords;
if (val.hasConfidenceRating && val.confidence > 0) {
_confidence = val.confidence;
}
}));
}
} else {
setState(() => _isListening = false);
_speech.stop();
}
}
}
Error

Issues with ToDo list

I have several questions:
How can you create a todo list with deletable tiles, usable checkboxes and how can u save data, that a user put in?
I have currently found a tutorial with stateless tiles where you cant use the tickboxes or delete the tiles...
In my case the whole stuff gets wiped and the toDO list is trash...
Thank you for your help ^^
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: ToDo()));
class ToDo extends StatefulWidget {
#override
_ToDoState createState() => _ToDoState();
}
class _ToDoState extends State<ToDo> {
List<String> products = ['Tomate', 'Käse', 'Lauch', 'Paprika' ,'Wein'];
void addItem(String item) {
setState(() {
products.add(item);
});
Navigator.of(context).pop();
}
void newEntry() {
showDialog<AlertDialog>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: TextField(
onSubmitted: addItem,
),
);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("To-Do-App"),
backgroundColor: Color.fromRGBO(35, 152, 185, 100),
),
body:
ListView.builder(
itemCount: products.length,
itemBuilder: (context, i) {
return ToDoItem( products[i] );
},
),
floatingActionButton: FloatingActionButton(
onPressed: newEntry,
child: Icon(Icons.add),
),
);
}
}
class ToDoItem extends StatelessWidget {
final String title;
const ToDoItem(this.title);
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 22),
child: ListTile(
contentPadding: EdgeInsets.symmetric(vertical: 8.0),
leading: Checkbox(
value: false,
),
title: Text(
title,
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.w600,
color: Colors.black54),
),
trailing: Icon(Icons.delete_outline),
),
);
}
}

How can I solve Flutter navigation BuilderContext subtype error?

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_auths/pages/searchservice.dart';
import 'package:flutter_auths/pages/tasks.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var queryResultSet = [];
var tempSearchStore = [];
initiateSearch(value) {
if (value.length == 0) {
setState(() {
queryResultSet = [];
tempSearchStore = [];
});
}
var capitalizedValue =
value.substring(0, 1).toUpperCase() + value.substring(1);
if (queryResultSet.length == 0 && value.length == 1) {
SearchService().searchByName(value).then((QuerySnapshot docs) {
for (int i = 0; i < docs.documents.length; ++i) {
queryResultSet.add(docs.documents[i].data);
}
});
} else {
tempSearchStore = [];
queryResultSet.forEach((element) {
if (element['Username'].startsWith(capitalizedValue)) {
setState(() {
tempSearchStore.add(element);
});
}
});
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('Firestore search'),
),
body: ListView(children: <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: TextField(
onChanged: (val) {
initiateSearch(val);
},
decoration: InputDecoration(
prefixIcon: IconButton(
color: Colors.black,
icon: Icon(Icons.arrow_back),
iconSize: 20.0,
onPressed: () {
Navigator.of(context).pop();
},
),
contentPadding: EdgeInsets.only(left: 25.0),
hintText: 'Search by name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0))),
),
),
SizedBox(height: 10.0),
GridView.count(
padding: EdgeInsets.only(left: 10.0, right: 10.0),
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0,
primary: false,
shrinkWrap: true,
children: tempSearchStore.map((element) {
return buildResultCard(element);
}).toList())
]));
}
}
Widget buildResultCard(data) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
elevation: 2.0,
child: Container(
child: Column(
children: <Widget> [ Text(data['Username'],
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
),
),
RaisedButton(
onPressed: () {
Navigator.push(
data,
MaterialPageRoute(builder: (data) => ProfilePage()),
);
},
child: const Text('asd', style: TextStyle(fontSize: 12)),
),
]
)
)
);
}
Here I search for a user from database then it shows me the results in cards, I added a button and by clicking on it I want to navigate the page to another page but the following error occures.
this is the error and the app
So I want to click on specific user’s button and redirect the page to that user’s profile. How can I do that?
You are getting this error because instead of passing buildContext you are passing data.
So your error gets removed if you change you code from this
Navigator.push(
data,
MaterialPageRoute(builder: (data) => ProfilePage()),
);
to
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfilePage(username: data['Username']))
);
This is how you should pass the data to the Profile Page.
Also
Widget buildResultCard(data)
be changed to
Widget buildResultCard(context, data)
and
buildResultCard(element);
to
buildResultCard(context, element);
First, you need to Navigate to that page with data like
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfilePage(profileData: data))
);
then you need to receive that data
class ProfilePage extends StatefulWidget {
var profileData;
ProfilePage({this.profileData});
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(widget.profileData['username']),
),
);
}
}
You can pass and receive data in another way
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProfilePage(),settings: RouteSettings(arguments: data))
);
then
class ProfilePage extends StatefulWidget {
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
var profileData;
#override
Widget build(BuildContext context) {
profileData=ModalRoute.of(context).settings.arguments;
return Scaffold(
body: Center(
child: Text(profileData['username']),
),
);
}
}