Flutter Firebase Phone Authentication crashes the app on iOS when verifying - firebase

I am using phone authentication to link with google authentication. This implementation was working before but all of a sudden just crashing the app.
here is my full code
import 'package:FaithMeetsLove/controller/authentication.dart';
import 'package:another_flushbar/flushbar.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
import 'package:pin_code_text_field/pin_code_text_field.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../constant/contact.dart';
import 'gender.dart';
class NumberOTP extends StatefulWidget {
NumberOTP({Key key}) : super(key: key);
#override
_NumberOTPState createState() => _NumberOTPState();
}
class _NumberOTPState extends State<NumberOTP> {
final phoneNumberInput = TextEditingController();
final otpNumberInput = TextEditingController();
String number123 = '';
PhoneNumber number = PhoneNumber(isoCode: 'AF');
String verificationId;
Future<bool> signIn() async {
try {
//!here is where phone auth start
final AuthCredential phoneCredential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: otpNumberInput.text,
);
final getuser =
await (auth.currentUser?.linkWithCredential(phoneCredential));
final user = getuser?.user;
await firestore.collection('users').doc(user?.uid).update({
'phoneNumber': user?.phoneNumber,
});
SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setBool('phoneAuth', true);
return true;
} catch (e) {
return false;
}
}
Future<void> phoneAuth(BuildContext context) async {
try {
final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verId) {
verificationId = verId;
};
final PhoneCodeSent codeSent = (String verId, [int forceCodeResend]) {
verificationId = verId;
setState(() {
next = false;
});
};
final PhoneVerificationCompleted verificationCompleted =
(phoneAuthCredential) {
print('verified');
};
final PhoneVerificationFailed verificationFailed = (error) async {
print('$error');
await Flushbar(
title: 'Error !!!',
message: 'Error Phone Verification $error',
duration: Duration(seconds: 3),
).show(context);
};
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: number123,
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
timeout: Duration(seconds: 10),
);
} catch (e) {
await Flushbar(
title: 'OTP Error !!!',
message: 'Error in OTP $e',
duration: Duration(seconds: 3),
).show(context);
}
}
bool next = true;
bool hasError = false;
bool checkIfIsValid = false;
Widget inputNumber() {
return Scaffold(
body: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
FocusScope.of(context).unfocus();
},
child: ProgressHUD(
child: Builder(
builder: (context) => Container(
padding: const EdgeInsets.all(17.0),
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Constants.color1,
Constants.color2,
],
),
),
child: Center(
child: Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: CircleAvatar(
radius: 60,
backgroundColor: Colors.white.withOpacity(0.4),
child: Icon(
FontAwesomeIcons.phoneAlt,
color: Colors.white,
size: 30,
),
),
),
Flexible(
child: Text(
'Phone Number',
style: GoogleFonts.raleway(
textStyle: TextStyle(
fontSize: 35,
color: Colors.white,
),
),
),
),
Flexible(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
'Input Your Phone Number that will be Associated with your account',
textAlign: TextAlign.center,
style: GoogleFonts.raleway(
textStyle: TextStyle(
fontSize: 15,
color: Colors.white,
),
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 15.0, horizontal: 180),
child: Divider(
thickness: 5,
color: Colors.white.withOpacity(0.6),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: InternationalPhoneNumberInput(
maxLength: 11,
inputDecoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.white, width: 1.0),
borderRadius: BorderRadius.circular(15),
),
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.white, width: 1.0),
borderRadius: BorderRadius.circular(15),
),
hintText: 'Number',
hintStyle: TextStyle(
color: Colors.white,
),
),
textStyle:
TextStyle(color: Colors.white, fontSize: 25),
onInputChanged: (PhoneNumber number) {
number123 = number.phoneNumber;
print(number.phoneNumber);
},
onInputValidated: (bool value) {
checkIfIsValid = value;
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle:
TextStyle(color: Colors.white, fontSize: 18),
initialValue: number,
textFieldController: phoneNumberInput,
formatInput: false,
keyboardType: TextInputType.numberWithOptions(
signed: true, decimal: true),
inputBorder: OutlineInputBorder(),
onSaved: (PhoneNumber number) {
print('On Saved: $number');
},
),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 18.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
height: 60,
child: TextButton(
onPressed: () async {
final progress = ProgressHUD.of(context);
progress?.showWithText('Sending OTP');
try {
if (checkIfIsValid) {
await phoneAuth(context);
progress?.dismiss();
await Flushbar(
title: 'OTP',
message: 'OTP Sent',
duration: Duration(seconds: 3),
).show(context);
} else {
progress?.dismiss();
await Flushbar(
title: 'Ops!',
message:
'Correct Your Phone Number........',
duration: Duration(seconds: 3),
).show(context);
}
} catch (e) {
await Flushbar(
title: 'Ops!',
message: '$e',
duration: Duration(seconds: 3),
).show(context);
}
},
child: Icon(
Icons.check,
color: Colors.red,
),
style: TextButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(18.0),
side: BorderSide(color: Colors.red)),
backgroundColor: Colors.white,
),
),
),
),
],
),
)
],
),
),
),
),
),
),
),
);
}
Widget inputOtp() {
return Scaffold(
body: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
FocusScope.of(context).unfocus();
},
child: ProgressHUD(
child: Builder(
builder: (context) => Container(
padding: const EdgeInsets.all(17.0),
height: double.infinity,
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Constants.color1,
Constants.color2,
],
),
),
child: Center(
child: Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(10.0),
child: CircleAvatar(
radius: 60,
backgroundColor: Colors.white.withOpacity(0.4),
child: Icon(
Icons.phone_android_rounded,
color: Colors.white,
size: 60,
),
),
),
Flexible(
child: Text(
'We sent a code',
style: GoogleFonts.raleway(
textStyle: TextStyle(
fontSize: 35,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
Flexible(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
'Enter the Secure OTP that was sent to the associated number',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 15.0, horizontal: 180),
child: Divider(
thickness: 5,
color: Colors.white.withOpacity(0.6),
),
),
Container(
child: PinCodeTextField(
autofocus: false,
controller: otpNumberInput,
hideCharacter: false,
highlight: true,
highlightColor: Colors.blue,
defaultBorderColor: Colors.black,
hasTextBorderColor: Colors.green,
highlightPinBoxColor: Colors.white,
maxLength: 6,
hasError: hasError,
//maskCharacter: "😎",
onTextChanged: (text) {
setState(() {
hasError = false;
});
},
onDone: (text) {
print("DONE $text");
print("DONE CONTROLLER ${otpNumberInput.text}");
},
pinBoxWidth: 50,
pinBoxHeight: 50,
hasUnderline: false,
wrapAlignment: WrapAlignment.spaceAround,
pinBoxDecoration:
ProvidedPinBoxDecoration.roundedPinBoxDecoration,
pinTextStyle:
TextStyle(fontSize: 15.0, color: Colors.black),
pinTextAnimatedSwitcherTransition:
ProvidedPinBoxTextAnimation.scalingTransition,
pinTextAnimatedSwitcherDuration:
Duration(milliseconds: 300),
highlightAnimationBeginColor: Colors.black,
highlightAnimationEndColor: Colors.white12,
keyboardType: TextInputType.number,
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 18.0,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Container(
height: 60,
child: TextButton(
onPressed: () async {
final progress = ProgressHUD.of(context);
progress?.showWithText('Please wait');
try {
final isSiging = await signIn();
if (isSiging) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => SelectGender(),
),
);
progress?.dismiss();
} else {
progress?.dismiss();
await Flushbar(
title: 'Ops!',
message:
'Number already use or Wrong OTP',
duration: Duration(seconds: 3),
).show(context);
}
} catch (e) {
progress?.dismiss();
await Flushbar(
title: 'Ops!',
message: '$e',
duration: Duration(seconds: 3),
).show(context);
}
},
child: Icon(
Icons.check,
color: Colors.red,
),
style: TextButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(18.0),
side: BorderSide(color: Colors.red)),
backgroundColor: Colors.white,
),
),
),
),
],
),
)
],
),
),
),
),
),
),
),
);
}
#override
Widget build(BuildContext context) {
return next ? inputNumber() : inputOtp();
}
Widget makeInput({
hintText,
TextEditingController controller,
}) {
return TextField(
controller: controller,
textAlign: TextAlign.center,
cursorColor: Colors.white,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
hintText: hintText,
filled: true,
fillColor: Colors.white.withOpacity(0.3),
hintStyle: TextStyle(color: Colors.white.withOpacity(0.7)),
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red.withOpacity(0.2), width: 1.0),
borderRadius: BorderRadius.circular(15),
),
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red.withOpacity(0.2), width: 1.0),
borderRadius: BorderRadius.circular(15),
),
),
style: TextStyle(
fontSize: 25,
color: Colors.white,
),
);
}
}
here is info.plist
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.39...4890211-klbqki2me0m8fjccmb......</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>fb368586070589462</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>FacebookAppID</key>
<string>368586070589462</string>
<key>FacebookDisplayName</key>
<string>FaithMeetsLove</string>
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fbapi20130214</string>
<string>fbapi20130410</string>
<string>fbapi20130702</string>
<string>fbapi20131010</string>
<string>fbapi20131219</string>
<string>fbapi20140410</string>
<string>fbapi20140116</string>
<string>fbapi20150313</string>
<string>fbapi20150629</string>
<string>fbapi20160328</string>
<string>fbauth</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
i have even run on debug still yet no error printed out. Immediately i click to verify the number it will just crash the app.

Related

Search bar in flutter app fetch articles from WordPress API

I guys, I have a News Flutter app that fetch articles from WordPress API,I have this code in my app but I don't know how to show up articles from search bar.
As you can see in the body of the Home page I have a busy body homepage because there are tabs widgets to show up.
I share screens to understand my case.
Is there another way to show up results maybe using a search delegate?
HomePage
searchbar page
Empty searchbar when I search keyword, no results
Home screen with tabs to load
class SearchBar extends StatefulWidget{
final List<Article> posts;
const SearchBar({Key? key, required this.posts,}) : super(key: key);
#override
_SearchBarState createState() => _SearchBarState();
}
class _SearchBarState extends State<SearchBar> {
final List<Article> _searchedPost = [];
late List<Article> _searchedArticles = [];
late final data;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
decoration: const InputDecoration(
hintText: "Cerca Articolo",
border: InputBorder.none,
),
onChanged: (val) {
setState(() {
_searchedArticles = widget.posts.where((element) => element.title!.contains(val)).toList();
});
},
),
),
body: _searchedArticles.isEmpty ?
Scaffold(
body: Padding(padding: const EdgeInsets.all(12),
child: Column(
children: [
Image.asset("assets/images/search-illustration.png", height: 230,),
const SizedBox(height: 20,),
const Text('Nessun articolo trovato!',
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 20,),
const Text('Inserisci meglio le lettere o parole chiave dell’articolo che stai cercando e riprova.',
style: TextStyle(
fontSize: 16.0,
color: Colors.black54,
fontWeight: FontWeight.w400,
),
),
const SizedBox(height: 30,),
MaterialButton(
height: 50,
elevation: 0,
color: Colors.blue[900],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: const [
Text('Torna alla home', style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w600),),
],
),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => HomePage(),
),
);
},
),
],
),
),
) : ListView.builder(
itemCount: _searchedArticles.length,
itemBuilder: (context, i) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Card(
margin: const EdgeInsets.all(10),
elevation: 5,
shadowColor: Colors.black26,
child: InkWell(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
//data["_embedded"]["wp:featuredmedia"][0]["link"],),
_searchedArticles[i].urlImage == null
? const Text("Nessuna immagine caricata")
: Image.network(data["_embedded"]["wp:featuredmedia"][0]["link"],
width: double.infinity,
height: 220,
fit: BoxFit.cover,
),
// Title article
Column(
children: [
Padding(
padding: const EdgeInsets.only(
left: 16, top: 16, bottom: 16),
child: Row(
children: [
Expanded(
child: Text(_searchedArticles[i].title as String,
maxLines: 3,
overflow: TextOverflow.clip,
softWrap: true,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
,
),
),
),
],
),
)
],
),
],
),
),
onTap: () {
if (_searchedPost[i] != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticlePage(
data: _searchedPost[i],
),
),
);
}
},
),
),
],
);
},
),
);
}
}```
Home page
class HomePage extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<HomePage> with SingleTickerProviderStateMixin {
TabController? _tabController;
final List<Tab> topTabs = <Tab>[
const Tab(child: Text("Notizie")),
const Tab(child: Text("Fiscalità")),
const Tab(child: Text("Gestione")),
const Tab(child: Text("Business")),
const Tab(child: Text("Documentazione")),
];
#override
void initState() {
/// Start tabs articles
_tabController = TabController(length: topTabs.length, initialIndex: 0, vsync: this)..addListener(() {setState(() {});});
super.initState();
/// End tabs articles
}
/// tabs
Future<bool> _onWillPop() async {
if (_tabController?.index == 0) {
await SystemNavigator.pop();
}
Future.delayed(const Duration(microseconds: 200), () {
_tabController?.index = 0;
});
return _tabController?.index == 0;
}
final _scaffoldKey = GlobalKey<ScaffoldState>();
///
///
/// Search page
final List<Article> _posts = [];
#override
Widget build(BuildContext context) {
return Container(
child: WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
key: _scaffoldKey,
extendBody: true,
drawer: NavbarMenu(),
backgroundColor: const Color(0xFFFAFAFA),
appBar: AppBar(
elevation: 0,
leading: Builder(
builder: (BuildContext context) {
return GestureDetector(
child: Center(
child: IconButton(
icon: const Icon(
Icons.dehaze_outlined,
color: Colors.white,
),
onPressed: () {
Scaffold.of(context).openDrawer();
},
),
),
);
},
),
backgroundColor: Colors.blue[900],
centerTitle: true,
title: Image.asset('assets/images/bird.png', fit: BoxFit.contain, height: 32,),
/// Action search icon
actions: <Widget>[
/// First search icon
IconButton(
icon: const Icon(Icons.search, color: Colors.white,),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context)=> SearchBar(posts: _posts,)
));
},
),
],
/// Bottom tab bar
bottom: TabBar(
controller: _tabController,
indicatorColor: const Color(0xFFF9E14B),
tabs: topTabs,
indicator: const UnderlineTabIndicator(
borderSide: BorderSide(
width: 4.0,
color: Color(0xFFF9E14B),
),
insets: EdgeInsets.symmetric(horizontal: 10.0, vertical: 0),
),
labelColor: Colors.yellow,
unselectedLabelColor: Colors.white,
isScrollable: true,
labelStyle: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
fontFamily: "Raleway"),
unselectedLabelStyle: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 14,
),
),
),
/// Body
body: TabBarView(
controller: _tabController,
children: const [
//SearchBar(posts: [],),
NewsPage(),
FiscalitaPage(),
GestionePage(),
BusinessPage(),
DocumentazionePage(),
],
),
///
),
),
);
}```

FormatException: Unexpected character (at character 1) error while using email_auth package

#Hello there! I am using email_auth: ^0.0.1+4 Package to confirm the user email also it worked fine for few days and I also registered 2 3 users but suddenly it has started showing this FormatException: Unexpected character (at character 1) and DOCTYPE html error. I have added signup file Please check and help. Thank you.#
SignUp Page
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:vanfly/common.dart';
import 'package:vanfly/providers/user_provider.dart';
import 'package:vanfly/screens/home.dart';
import 'package:vanfly/widgets/loading.dart';
import 'package:email_auth/email_auth.dart';
bool verified = false;
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _formKey = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
TextEditingController _email = TextEditingController();
TextEditingController _password = TextEditingController();
TextEditingController _name = TextEditingController();
TextEditingController otp = TextEditingController();
bool hidePass = true;
void sendOTP() async {
EmailAuth.sessionName = 'Vanfly';
var res = await EmailAuth.sendOtp(receiverMail: _email.value.text);
if (res) {
_key.currentState.showSnackBar(SnackBar(
content: Text("An OTP has sent to your email please verify")));
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
}
}
bool verifyOTP(){
var res = EmailAuth.validate(receiverMail: _email.value.text, userOTP: otp.value.text);
if (res) {
return verified = true;
} else {
_key.currentState
.showSnackBar(SnackBar(content: Text('Something went wrong')));
return verified = false;
}
}
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
return Scaffold(
key: _key,
body: user.status == Status.Authenticating
? Loading()
: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.grey[350],
blurRadius:
20.0, // has the effect of softening the shadow
)
],
),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
alignment: Alignment.topCenter,
child: Image(
image: AssetImage(
'images/vanfly Logo/vanfly_logo.png'),
width: 300,
height: 300,
)),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _name,
decoration: InputDecoration(
hintText: "Full name",
icon: Icon(Icons.person_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The name field cannot be empty";
}
return null;
},
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
keyboardType: TextInputType.emailAddress,
controller: _email,
decoration: InputDecoration(
hintText: "Email",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Verify')),
icon: Icon(Icons.alternate_email),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.2),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(keyboardType: TextInputType.number,
controller: otp,
decoration: InputDecoration(
hintText: "otp",
suffixIcon: TextButton(
onPressed: () {
sendOTP();
},
child: Text('Resend'),
),
icon: Icon(Icons.pin),
border: InputBorder.none),
),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(10.0),
color: Colors.grey.withOpacity(0.3),
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(left: 12.0),
child: ListTile(
title: TextFormField(
controller: _password,
obscureText: hidePass,
decoration: InputDecoration(
hintText: "Password",
icon: Icon(Icons.lock_outline),
border: InputBorder.none),
validator: (value) {
if (value.isEmpty) {
return "The password field cannot be empty";
} else if (value.length < 6) {
return "the password has to be at least 6 characters long";
}
return null;
},
),
trailing: IconButton(
icon: Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
hidePass = !hidePass;
});
}),
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
14.0, 8.0, 14.0, 8.0),
child: Material(
borderRadius: BorderRadius.circular(20.0),
color: Colors.pinkAccent,
elevation: 0.0,
child: MaterialButton(
onPressed: () async {
verifyOTP();
if (verified == true &&
_formKey.currentState.validate()) {
if (!await user.signUp(_name.text,
_email.text, _password.text)) {
// ignore: deprecated_member_use
_key.currentState.showSnackBar(
SnackBar(
content:
Text("Sign up failed")));
return;
}
changeScreenReplacement(
context, MyHomePage());
}
},
minWidth: MediaQuery.of(context).size.width,
child: Text(
"Sign up",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
)),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Text(
"I already have an account",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black, fontSize: 16),
))),
],
)),
),
),
],
),
);
}
}
Error
I/flutter ( 5091): Email ID is valid
I/flutter ( 5091): --This error is from the package--
I/flutter ( 5091): FormatException: Unexpected character (at character 1)
I/flutter ( 5091): <!DOCTYPE html>
I/flutter ( 5091): ^
I/flutter ( 5091): --End package error message--
The error is coming from the package itself.
The endpoint that the package calls to send the OTP is down and so it returns an error page instead of the JSON the package expected. This causes an error in parsing the HTML which is why the error says:
FormatException: Unexpected character (at character 1)
<!DOCTYPE html>
^
I'll advise you to use a different service like firebase_auth for this or create an issue on the project.

Error "The method '[]' was called on null. Receiver: null Tried calling: []("0tm2JqPY0oNq5vSM74BqOufhGao1")"

I am getting this error in the poll post Page after added the voting feature to it:
The new method I added is handleTotalVotePosts to handle the count of userPostPolls(in line number 178).
I think the error is getting the userId or something which i am not Sure .
I am not sure what is actually wrong here
The method '[]' was called on null.
Receiver: null
Tried calling: []("0tm2JqPY0oNq5vSM74BqOufhGao1")
But code seems to be correct
This my **pollPost.dart**
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:justpoll/libmodels/user_model.dart';
import 'package:justpoll/screens/chat/chat_data.dart';
import 'package:justpoll/widgets/progress.dart';
import 'package:justpoll/widgets/toast_text.dart';
import '../Constants.dart';
import 'package:justpoll/widgets/custom_image.dart';
import 'package:animated_button/animated_button.dart';
class PollPost extends StatefulWidget {
final String pollPostId;
final String mediaUrl;
final String ownerId;
final String username;
final String caption;
final String category;
final String colorTheme;
final Timestamp duration;
final String question;
final dynamic votesTotal;
final String optText1;
final String optText2;
final String optText3;
final String optText4;
final String optemo1;
final String optemo2;
final String optemo3;
final String optemo4;
final String optCount1;
final String optCount2;
final String optCount3;
final String optCount4;
PollPost({
this.pollPostId,
this.mediaUrl,
this.ownerId,
this.username,
this.caption,
this.category,
this.colorTheme,
this.duration,
this.question,
this.votesTotal,
this.optText1,
this.optText2,
this.optText3,
this.optText4,
this.optemo1,
this.optemo2,
this.optemo3,
this.optemo4,
this.optCount1,
this.optCount2,
this.optCount3,
this.optCount4,
});
factory PollPost.fromDocument(DocumentSnapshot doc) {
return PollPost(
pollPostId: doc['pollPostid'],
mediaUrl: doc['mediaUrl'],
ownerId: doc['ownerId'],
username: doc['username'],
caption: doc['caption'],
category: doc['category'],
colorTheme: doc['colorTheme'],
duration: doc['Duration'],
question: doc['Question'],
votesTotal: doc['votesTotal'],
optText1: doc["options"]["1"]["optionText1"],
optText2: doc["options"]["2"]["optionText2"],
optText3: doc["options"]["3"]["optionText3"],
optText4: doc["options"]["4"]["optionText4"],
optemo1: doc["options"]["1"]["optionEmoji1"],
optemo2: doc["options"]["2"]["optionEmoji2"],
optemo3: doc["options"]["3"]["optionEmoji3"],
optemo4: doc["options"]["4"]["optionEmoji4"],
// optCount1: doc["options"]["1"]["optionCount1"],
// optCount2: doc["options"]["2"]["optionCount2"],
// optCount3: doc["options"]["3"]["optionCount3"],
// optCount4: doc["options"]["4"]["optionCount4"],
);
}
int getreactionsTotalCount(votesTotal) {
if (votesTotal == null) {
return 0;
}
int count = 0;
votesTotal.values.forEach((val) {
if (val = true) {
count += 1;
}
});
return count;
}
#override
_PollPostState createState() => _PollPostState(
pollPostId: this.pollPostId,
mediaUrl: this.mediaUrl,
ownerId: this.ownerId,
username: this.username,
caption: this.caption,
category: this.category,
colorTheme: this.colorTheme,
duration: this.duration,
question: this.question,
optText1: this.optText1,
optText2: this.optText2,
optText3: this.optText3,
optText4: this.optText4,
optemo1: this.optemo1,
optemo2: this.optemo2,
optemo3: this.optemo3,
optemo4: this.optemo4,
votesTotalCount: getreactionsTotalCount(this.votesTotal),
);
}
class _PollPostState extends State<PollPost> {
GlobalKey floatingKey = LabeledGlobalKey("Floating");
bool isFloatingOpen = false;
OverlayEntry floating;
static FirebaseAuth auth = FirebaseAuth.instance;
final userRef = FirebaseFirestore.instance.collection("users");
final pollPostsRef = FirebaseFirestore.instance.collection("pollPosts");
final String currentUserId = auth.currentUser?.uid;
final String pollPostId;
final String mediaUrl;
final String ownerId;
final String username;
final String caption;
final String category;
final String colorTheme;
final Timestamp duration;
final String question;
final String optText1;
final String optText2;
final String optText3;
final String optText4;
final String optemo1;
final String optemo2;
final String optemo3;
final String optemo4;
int votesTotalCount;
Map votesTotal;
bool isVoted;
_PollPostState({
this.pollPostId,
this.mediaUrl,
this.ownerId,
this.username,
this.caption,
this.category,
this.colorTheme,
this.duration,
this.question,
this.votesTotal,
this.votesTotalCount,
this.optText1,
this.optText2,
this.optText3,
this.optText4,
this.optemo1,
this.optemo2,
this.optemo3,
this.optemo4,
});
handleTotalVotePosts() {
bool _isVoted = votesTotal[currentUserId] == true;
if (_isVoted) {
pollPostsRef
.doc(ownerId)
.collection('usersPollPosts')
.doc(pollPostId)
.update({'votesTotal.$currentUserId': false});
setState(() {
votesTotalCount -= 1;
isVoted = false;
votesTotal[currentUserId] = false;
});
} else if (!_isVoted) {
pollPostsRef
.doc(ownerId)
.collection('usersPollPosts')
.doc(pollPostId)
.update({'votesTotal.$currentUserId': true});
setState(() {
votesTotalCount += 1;
isVoted = true;
votesTotal[currentUserId] = true;
});
}
}
OverlayEntry createFloating() {
RenderBox renderBox = floatingKey.currentContext.findRenderObject();
Offset offset = renderBox.localToGlobal(Offset.zero);
return OverlayEntry(builder: (context) {
return Positioned(
left: offset.dx,
top: offset.dy - 70,
child: Material(
color: Colors.transparent,
elevation: 20,
child: ClipRRect(
borderRadius: BorderRadius.circular(40.0),
child: Container(
padding: EdgeInsets.all(5.0),
height: 50,
color: MyColors.black,
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
handleTotalVotePosts();
toastMessage("You voted for $optText1 $optemo1");
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child:
Text(optemo1, style: TextStyle(fontSize: 20.0)))),
Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
toastMessage("You voted for $optText2 $optemo2");
setState(() {
handleTotalVotePosts();
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child:
Text(optemo2, style: TextStyle(fontSize: 20.0)))),
optText3.isEmpty
? Text("")
: Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
handleTotalVotePosts();
toastMessage(
"You voted for $optText3 $optemo3");
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child: Text(optemo3,
style: TextStyle(fontSize: 20.0)))),
optText4.isEmpty
? Text("")
: Padding(
padding: const EdgeInsets.all(5.0),
child: AnimatedButton(
onPressed: () {
handleTotalVotePosts();
toastMessage(
"You voted for $optText4 $optemo4");
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
duration: 20,
enabled: true,
width: 30,
height: 30,
color: MyColors.black,
shadowDegree: ShadowDegree.light,
child: Text(optemo4,
style: TextStyle(fontSize: 20.0)))),
],
),
),
),
),
);
});
}
buildPollPostHeader() {
return FutureBuilder(
future: userRef.doc(ownerId).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
UserModel user = UserModel.fromMap(snapshot.data.data());
return ListTile(
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
backgroundColor: Colors.grey,
),
title: GestureDetector(
onTap: () => toastMessage("showing profile"),
child: Text(
user.username,
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
),
subtitle: Text(category),
trailing: IconButton(
onPressed: () => toastMessage("pop up menu"),
icon: Icon(Icons.more_vert),
),
);
},
);
}
buildPollPostCenter() {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
question,
style: TextType.boldHeading,
),
),
mediaUrl == null
? Center(
child: Container(
height: 30.0,
))
: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: chachedNetworkImage(
mediaUrl,
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: Column(
children: [
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
optText1,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo1),
SizedBox(
width: 25.0,
),
Text(
optText2,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo2),
],
),
],
),
SizedBox(height: 13.0),
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
optText3,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo3),
SizedBox(
width: 25.0,
),
Text(
optText4,
style: TextStyle(
color: MyColors.offBlack,
fontSize: 16.0,
),
),
Text(optemo4),
],
),
],
),
],
),
),
],
);
}
buildPollPostFooter() {
return Column(
children: [
Align(
alignment: Alignment.bottomLeft,
child: Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(padding: EdgeInsets.only(top: 40.0, left: 20.0)),
isVoted
? GestureDetector(
key: floatingKey,
onTap: () {
setState(() {
if (isFloatingOpen)
floating.remove();
else {
floating = createFloating();
Overlay.of(context).insert(floating);
}
isFloatingOpen = !isFloatingOpen;
});
},
child: Icon(
Icons.poll,
color: MyColors.offBlack,
size: 28.0,
),
)
: Icon(Icons.check_circle),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => toastMessage("show comments"),
child: Icon(
Icons.chat,
color: MyColors.offBlack,
size: 28.0,
),
),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => toastMessage("saved successfully"),
child: Icon(
Icons.bookmark,
color: MyColors.offBlack,
size: 28.0,
),
),
Padding(padding: EdgeInsets.only(right: 20.0)),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
GestureDetector(
onTap: () => toastMessage("sharing with friends"),
child: Align(
alignment: Alignment.topRight,
child: Icon(
Icons.send,
color: MyColors.offBlack,
size: 28.0,
),
),
),
Padding(padding: EdgeInsets.only(right: 25.0)),
],
),
),
],
),
),
),
Row(
children: [
Container(
margin: EdgeInsets.only(left: 20.0, top: 5.0),
child: Text(
"$votesTotalCount votes",
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
),
Container(
margin: EdgeInsets.only(left: 20.0, top: 5.0),
child: Text(
"expiring in 4 days",
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
)
],
),
Padding(
padding: const EdgeInsets.only(top: 5.0, bottom: 10.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
"$username ",
style: TextStyle(
color: MyColors.black,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: Text(caption),
),
],
),
)
],
);
}
#override
Widget build(BuildContext context) {
isVoted = (votesTotal[currentUserId] == true);
return Card(
elevation: 1.0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
buildPollPostHeader(),
buildPollPostCenter(),
buildPollPostFooter(),
],
),
);
}
}
Please help me to get out of this bug.
Thank you :)
Please write the below code inside your handleTotalVotePosts method:
if(votesTotal == null){
return;
}

Retrieving Data From Firestore in time

I have looked all over the internet for how to fix this problem and I can't find a solution anywhere. I am using flutter with firestore to make an app. I want to make it so when the user logins into the app at the top shows their name (simple right). I can get data from firestore:
Future<void> getName() async {
print("Attemping to get name!");
final firestoreInstance = await FirebaseFirestore.instance;
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
await firestoreInstance.collection("Users").doc(uid).get().then((value) {
print("Name: " + value.data()["firstName"]);
info.firstName=((value.data()["firstName"]));
})
class info {
static String firstName;
}
but it comes in too late so the app just says "Welcome back" As you can see here and not "Welcome back, Connor" As seen here
When I look in the console the function does run but the program doesn't wait for it and continues resulting in a null.
Thanks you
EDIT as requested UI code:
class Home extends StatelessWidget {
final DatabaseReference = FirebaseDatabase.instance;
final FirebaseAuth auth = FirebaseAuth.instance;
static String firstName;
static String lastName;
static String email;
static String companyName;
static bool isNewAccount = false;
static String name = "Welcome back";
Home();
#override
Widget build(BuildContext context) {
final User user = auth.currentUser;
final uid = user.uid;
final ref = DatabaseReference.reference();
if (isNewAccount == true) {
userSetup(firstName, lastName, email, companyName);
isNewAccount = false;
}
getName(); //does get the name from the database but name will error out as it doesn't get the name fast enough (or that's what I think)
name= "Welcome back, "+info.firstName;
return WillPopScope(
onWillPop: () async => false,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.cyan,
body: SingleChildScrollView(
child: Container(
margin:
EdgeInsets.only(top: MediaQuery.of(context).size.height / 16),
child: Column(
children: [
Container(
margin: EdgeInsets.only(bottom: 10),
child: Text(
name,
textAlign: TextAlign.center,
style: new TextStyle(
color: Colors.white,
fontSize: MediaQuery.of(context).size.width / 16,
),
),
),
Container(
width: 260,
height: 125,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"CHECK-IN",
style: new TextStyle(
color: Colors.white,
fontSize: 40.0,
),
),
color: Colors.grey[850],
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Checkin()));
},
),
),
Container(
width: 260,
height: 140,
padding: EdgeInsets.only(top: 20),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"CHECK-OUT",
style: new TextStyle(
color: Colors.white,
fontSize: 38.0,
),
),
color: Colors.grey[850],
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Checkout()));
},
),
),
Container(
margin: EdgeInsets.only(top: 55),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"Sign out: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"SIGN OUT",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
context.read<AuthenticationService>().signOut();
//return MyApp();
},
),
)
],
),
),
Container(
margin: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"View Stats: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"STATS",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Stats()));
},
),
),
],
),
),
Container(
margin: EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(right: 20),
child: Text(
"View Profile: ",
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
child: RaisedButton(
child: Text(
"PROFILE",
style: new TextStyle(
fontSize: 14.0,
color: Colors.white,
),
),
color: Colors.grey[700],
onPressed: () {
/*Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Stats()));*/
},
),
),
],
),
),
Container(
width: 240,
height: 55,
margin: EdgeInsets.only(
top: MediaQuery.of(context).size.height / 12),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Text(
"EMERGENCY REPORT",
style: new TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.grey[700],
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => EmergencyReport()));
},
),
),
],
),
),
),
),
),
);
}
static getAccountDetails(
String firstName1, String lastName1, String email1, String companyName1) {
firstName = firstName1;
lastName = lastName1;
email = email1;
companyName = companyName1;
isNewAccount = true;
}
static getFirstName(String nameFirst) {
name = "Welcome back, "+nameFirst;
}
}
FutureBuilder<DocumentSnapshot>(
future: firestoreInstance.collection("Users").doc(uid).get(),
builder: (_,snap){
return snap.hasData ? Text(snap.data.data()["firstName"]):CircularProgressIndicator();
},)
You need to convert StatelessWidget into StatefullWidget.
After that you have to write this in initState method
void initState() {
super.initState();
getName().then((){
setState(() {
name= "Welcome back, "+info.firstName;
});
});
}

Flutter : i got an error that State object for a widget that no longer appears in the widget tree

when i try to press on the send button to do the http request[which is done successflly] i got the below error, how can i solve it?!!
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _ForgetPasswordDialogState#95548(lifecycle state: defunct, not mounted
import 'dart:io';
import 'package:Zabatnee/common_app/provider/user_details_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class ForgetPasswordDialog extends StatefulWidget {
static const routeName = '/customeDialog';
final String title,description;
ForgetPasswordDialog({
this.title,
this.description,});
#override
_ForgetPasswordDialogState createState() => _ForgetPasswordDialogState();
}
class _ForgetPasswordDialogState extends State<ForgetPasswordDialog> {
final emailController = TextEditingController();
var _isLoading = false;
_showDialog(String title, String message) {
showDialog(
barrierDismissible: false,
context: context,
builder: (ctx) => WillPopScope(
onWillPop: () async => false,
child: new AlertDialog(
elevation: 15,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8))),
title: Text(
title,
style: TextStyle(color: Colors.white),
),
content: Text(
message,
style: TextStyle(color: Colors.white),
),
backgroundColor: Theme.of(context).primaryColor,
actions: <Widget>[
FlatButton(
child: Text(
'OK',
style: TextStyle(color: Theme.of(context).accentColor),
),
onPressed: () {
Navigator.of(context).pop();
setState(
() {
_isLoading = false;
},
);
},
)
],
),
),
);
}
Future<void> _forgetPassword (String email) async {
try{
setState(() {
_isLoading = true;
});
await Provider.of<UserDetailsProvider>(context, listen: false).forgetPassword(email);
print('code are sent via email');
} on HttpException catch (error) {
_showDialog('Authentication Failed', error.message);
} on SocketException catch (_) {
_showDialog('An error occured',
'please check your internet connection and try again later');
} catch (error) {
_showDialog('Authentication Failed',
'Something went wrong, please try again later');
}
setState(() {
_isLoading = false;
});
}
#override
void dispose() {
emailController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)
),
elevation: 8,
backgroundColor: Theme.of(context).accentColor,
child: dialogContent(context),
);
}
dialogContent(BuildContext context){
return Container(
padding: EdgeInsets.only(
top: 50,
right: 16,
left: 16,
bottom: 16,
),
margin: EdgeInsets.all(8),
width: double.infinity,
decoration: BoxDecoration(
color: Theme.of(context).accentColor,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(17),
boxShadow: [
BoxShadow(
color: Colors.black87,
blurRadius: 10.0,
offset: Offset(0.0,10.0),
)
]
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
widget.title,
style: TextStyle(
fontSize: 24,
),
),
SizedBox(
height: 20,
),
Text(widget.description, style: TextStyle(fontSize: 16),
),
SizedBox(
height: 20,
),
TextField(
controller: emailController,
style: TextStyle(color: Colors.white),
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(color:Theme.of(context).primaryColor)
),
fillColor: Colors.black87,
hintStyle: TextStyle(color:Colors.grey),
hintText: 'please enter your email',
labelText: 'Email',
labelStyle: TextStyle(color:Colors.white)
),
),
SizedBox(
height: 20,
),
Container(
width: double.infinity,
child: RaisedButton(
child: Text('Send'),
onPressed: (){
_isLoading
? CircularProgressIndicator()
: print(emailController.text);
_forgetPassword(emailController.text);
Navigator.of(context).pop();
}
),
),
Container(
width: double.infinity,
child: RaisedButton(
child: Text('Cancel'),
onPressed: (){
Navigator.of(context).pop();
}
),
),
],
),
);
}
}
Replace your
setState((){});
with
if (mounted) setState(() {});.
The mounted checks Whether the [State] object is currently in a tree. That way, you would be able to avoid the error.

Resources