failed assertion the relevant error-causing widget was textformfield - ios

Working on a flutter project and the code is stable on android every thing just working fine but when I want to debug at ios I am getting below errors. Could not understand why it is happing.
Any idea would help.
The following StackOverflowError was thrown building UnmanagedRestorationScope:
Stack Overflow
The relevant error-causing widget was
TextFormField
lib/…/login/loginPage.dart:63
When the exception was thrown, this was the stack
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4531 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
package:flutter/…/widgets/framework.dart:4531
The relevant error-causing widget was
TextFormField
and the error point it out to loginPage widget is
Padding(
padding: const EdgeInsets.only(top: 40, left: 40, right: 40),
child: TextFormField(
controller: viewModel.usernameText,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.account_circle,
color: qPrimaryColor,
),
hintText: PageTextConst.username,
labelText: PageTextConst.username,
labelStyle: const TextStyle(fontSize: 18)),
validator: (String? text) {
if (text!.isEmpty) {
return PageTextConst.enterUsername;
} else if (text.length < 6) {
return PageTextConst.falseUsername;
} else {
return "";
}
},
),
),
EDIT :
TextFormField controller
class LoginAuthViewModel extends BaseViewModel {
String versionName = "";
TextEditingController usernameText = TextEditingController();
TextEditingController passwordText = TextEditingController();

Padding(
padding: const EdgeInsets.only(top: 40, left: 40, right: 40),
child: SizedBox(
height:50,
width:100,
child: TextFormField(
controller: viewModel.usernameText,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.account_circle,
color: qPrimaryColor,
),
hintText: PageTextConst.username,
labelText: PageTextConst.username,
labelStyle: const TextStyle(fontSize: 18)),
validator: (String? text) {
if (text!.isEmpty) {
return PageTextConst.enterUsername;
} else if (text.length < 6) {
return PageTextConst.falseUsername;
} else {
return "";
}
},
),
),)
Simply add the sized box around the textformfield

Related

How to change textField header color?

How to change "Name" form TextField to Purple when Focus on this
i have a problem here that i try to solve this but it's not work
here is my code
class NewName extends StatefulWidget {
#override
_NewNomeState createState() => _NewNomeState();
}
class _NewNomeState extends State<NewName> {
#override
Widget build(BuildContext context) {
FocusNode myFocusNode = new FocusNode();
return Padding(
padding: const EdgeInsets.only(top: 0, left: 50, right: 50),
child: Container(
height: 60,
width: MediaQuery.of(context).size.width,
child: TextField(
focusNode: myFocusNode,
style: TextStyle(
color: Colors.purple,
),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.purple),
),
border: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.purple),
),
labelText: 'Name',
labelStyle: TextStyle(
fontFamily: 'SukumvitSetSemiBold',
fontSize: 14,
color: myFocusNode.hasFocus ? Colors.purple : Colors.black),
),
),
),
);
}
}
i have seen some Question that similar but i still don't know how to fixed it.
i'm too confuse here
please help
#Thank you very much
Well first you should declare your focusNode outside the build function, try moving FocusNode myFocusNode = new FocusNode(); outside of Build(BuildContext context) and check if that solved it.

Retrive data from reusable widget Textfield

In the following code, I am trying to get text by using controller data or by using var abc, abc is defined globally,
At the end of process I get null only.
Nither of data or var abc is working.
Widget _textField(BuildContext context, String label, TextInputType inputType,
TextEditingController data) {
return Container(
margin: const EdgeInsets.only(top: 8.0),
child: TextField(
style: Theme.of(context).textTheme.display1,
controller: data,
onChanged: (text) {
abc = text;
},
keyboardType: inputType,
decoration: InputDecoration(
labelStyle: Theme.of(context).textTheme.display1,
labelText: label,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0),
)),
),
);
}

The method 'ancestorStateOfType' was called on null. (Loop)

First of all, I'm a beginner at Flutter. I'm sending form data to login API and waiting for Success: OK message and UserID from API.
After getting UserID and Succes: OK response from API I'm sending the user to the dashboard with userID Here is my full code ;
class LoginScreen1 extends StatefulWidget {
#override
_LoginScreen1State createState() => _LoginScreen1State();
}
class _LoginScreen1State extends State<LoginScreen1> {
StreamSubscription streamSubscription;
String formMail, formSifre;
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
final formKey = GlobalKey<FormState>();
Login login;
Future<Login> _gonderiGetir(String formMail, String formSifre) async {
var url = 'MYURL';
var apiKey = "MYKEY";
var authPassword = this.formSifre;
var authMail = this.formMail;
debugPrint(this.formSifre);
var response = await http
.get('$url?Key=12345&mail=${this.formMail}&password=${this.formSifre}');
debugPrint("Sonuç Bekleniyor.");
if (response.statusCode == 200) {
_gelenDegeriBekle();
return Login.fromJsonMap(json.decode(response.body));
} else {
throw Exception("Baglanamadık ${response.statusCode}");
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
/*_gonderiGetir(formSifre, formMail).then((gelenDeger) {
login = gelenDeger;
debugPrint(login.UserID);
});*/
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Color(0xFFF7F8FA),
child: ListView(
children: <Widget>[
Stack(
children: <Widget>[
Container(
height: 250.0,
width: double.infinity,
),
Container(
height: 300.0,
width: double.infinity,
color: Color(0xFFFED428),
),
Positioned(
top: 225.0,
left: 15.0,
right: 15.0,
child: Material(
elevation: 3.0,
borderRadius: BorderRadius.circular(7.0),
child: Container(
height: 280.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(7.0),
color: Color(0xF6F6F6)),
),
)),
Positioned(
top: 75.0,
left: (MediaQuery.of(context).size.width / 2 - 50.0),
child: CircleAvatar(
radius: 50.0,
backgroundImage: NetworkImage(
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHVRLWSF79r7ABstLzXZi_pTcNkAMqx8EtWfIRZiA8mmqcl-Fsqw"),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(40, 235, 40, 15),
child: Form(
key: formKey,
autovalidate: true,
child: Column(
children: <Widget>[
TextFormField(
decoration: const InputDecoration(
labelStyle: TextStyle(color: Color(0xFFBBBFCB)),
icon: Icon(
Icons.person,
color: Color(0xFFBBBFCB),
),
labelText: 'Email *',
),
validator: (String girilenVeri) {
if (!girilenVeri.contains("#")) {
return "Geçerli bir mail adresi giriniz.";
} else
return null;
},
controller: _usernameController,
onSaved: (deger) => formMail = deger,
),
SizedBox(
height: 10.0,
),
TextFormField(
obscureText: true,
decoration: const InputDecoration(
labelStyle: TextStyle(color: Color(0xFFBBBFCB)),
icon: Icon(
Icons.lock,
color: Color(0xFFBBBFCB),
),
labelText: 'Şifre *',
),
validator: (String girilenVeri) {
if (girilenVeri.length < 6) {
return "Şifre 6 karakterden kısa olamaz.";
} else
return null;
},
controller: _passwordController,
onSaved: (deger) => formSifre = deger,
),
],
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(40, 420, 40, 15),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: double.infinity,
height: 50,
child: RaisedButton(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)),
color: Color(0xFFFED428),
onPressed: () {
if (formKey.currentState.validate()) {
formKey.currentState.save();
_gonderiGetir(formMail, formSifre);
debugPrint("OnPress Geldi");
}
},
child: Text(
"GİRİŞ",
style: TextStyle(fontSize: 20),
),
),
),
FlatButton(
onPressed: () {},
child: Text(
"Şifremi Unuttum",
style: TextStyle(
fontSize: 10, color: Color(0xFFBBBFCB)),
),
)
],
),
),
),
],
)
],
),
),
);
;
}
void _loginControl() {
if (formKey.currentState.validate()) {
formKey.currentState.save();
//formMail = _usernameController.text;
//formSifre= _passwordController.text;
debugPrint("$formSifre ve $formMail");
}
}
void _gelenDegeriBekle() {
_gonderiGetir(formSifre, formMail).then((gelenDeger) {
login = gelenDeger;
if (login.Status != null) {
debugPrint(login.UserID);
debugPrint(login.Status);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(),
),
);
}
});
}
}
But i'm getting this loop error:
flutter: asdasd
flutter: 387ddd00-f5ed-4c9c-87cf-45835bf77a53
flutter: OK
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'ancestorStateOfType' was called on null.
Receiver: null
Tried calling: ancestorStateOfType(Instance of 'TypeMatcher<NavigatorState>')
#0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
#1 Navigator.of (package:flutter/src/widgets/navigator.dart:1376:19)
#2 Navigator.pushReplacement (package:flutter/src/widgets/navigator.dart:1055:22)
#3 _LoginScreen1State._gelenDegeriBekle.<anonymous closure> (package:flutter_apppp/login.dart:247:19)
#4 _rootRunUnary (dart:async/zone.dart:1132:38)
#5 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#6 _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#7 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#8 Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#9 Future._complete (dart:async/future_impl.dart:473:7)
#10 _SyncCompleter.complete (dart:<…>
I keep getting this error message.
It looks like you have a loop that continuously runs in your widget. You're calling _gonderiGetir from _gelenDegeriBekle and also calling _gelenDegeriBekle from _gonderiGetir. So it's going to keep doing this forever, even after your widget has been removed (which is why context is null).
If you need to do something continuously, I'd recommend instead using a periodic timer to call it, and making sure that the timer is stopped when your widget is disposed!

Problem in Shared Preferenced in LoginScreen. Flutter

help and explain to me in detail please how can I modify my code. I am beginner in Flutter and now I am doing tasks, the essence of which is the use of Shared Preferenced in the Login Screen and saving the user data in FireBase. When the user first entered the data, he entered the Home screen, but when the user exits the application and tries to log in again, it should be that he does not need to enter the password and login again.
Also, I knocked out such an error
import 'package:flutter/material.dart';
import 'package:logining/home_screen/home_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginScreen extends StatefulWidget {
#override
LoginScreenState createState() {
return new LoginScreenState();
}
}
enum LoginStatus{
notSignIn,
signIn,
}
class LoginScreenState extends State<LoginScreen> {
LoginStatus _loginStatus = LoginStatus.notSignIn;
String _email, _password;
bool _obscureText = true;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
TextEditingController email = new TextEditingController();
TextEditingController password = new TextEditingController();
SharedPreferences sharedPreferences;
Future<FirebaseUser> _signInGoogle() async{
GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
GoogleSignInAuthentication gSa =await googleSignInAccount.authentication;
FirebaseUser user = await _auth.signInWithGoogle(
idToken: gSa.idToken,
accessToken: gSa.accessToken
);
print('User Name : ${user.displayName}');
return Navigator.push(context, MaterialPageRoute(builder: (context) => HomeScreen(user: user)));
}
safePref()async{
SharedPreferences preferences = await SharedPreferences.getInstance();
setState((){
preferences.setString('email', _email);
preferences.setString('password', _password);
preferences.commit();
});
}
var value;
getPref()async{
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
value = preferences.getInt('password');
value = preferences.getInt('email');
_loginStatus = value == 1 ? LoginStatus.signIn :LoginStatus.notSignIn;
});
}
#override
void initState(){
super.initState();
getPref();
}
#override
Widget build(BuildContext context) {
switch(_loginStatus){
case LoginStatus.notSignIn:
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
resizeToAvoidBottomPadding: false,
body: ListView(children: <Widget>[
Container(
child: Form(
key: _formKey,
autovalidate: true,
child: Column(
children: <Widget>[
SizedBox(
height: 50,
),
Padding(
child: Image.asset(
'images/logo.png',
width: 100.0,
height: 100.0,
),
padding: EdgeInsets.fromLTRB(50, 0, 50, 40),
),
Padding(
padding: EdgeInsets.fromLTRB(25, 0, 50, 10),
child: TextFormField(
controller: email,
validator: (email) {
if (email.isEmpty) {
return 'Provide an Email';
}
},
style: TextStyle(
color: Color(0xFF01579B),
fontSize: 18.0,
),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
),
hintText: 'Enter your Email',
labelText: "Email",
icon: Padding(
padding: EdgeInsets.only(top: 20.0),
child: Icon(Icons.email),
)),
onSaved: (email) => _email = email,
),
),
Padding(
padding: EdgeInsets.fromLTRB(25, 0, 50, 10),
child: TextFormField(
controller: password,
validator: (password) {
if (password.isEmpty) {
return 'Provide an password';
}
},
obscureText: _obscureText,
style: TextStyle(
color: Color(0xFF01579B),
fontSize: 18.0,
),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
),
hintText: 'Enter your password',
labelText: "Password",
icon: Padding(
padding: EdgeInsets.only(top: 15.0),
child: Icon(Icons.lock),
),
suffixIcon: GestureDetector(
onTap: () {
setState(() {
_obscureText = !_obscureText;
});
},
child: Icon(
_obscureText
? Icons.visibility
: Icons.visibility_off,
semanticLabel: _obscureText
? 'show password'
: 'hide password',
),
),
),
onSaved: (password) => _password = password,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: RaisedButton(
color: Color(0xFFD50000),
textColor: Color(0xFFFFFFFF),
child: Text('Login with Google'),
onPressed:(){ _signInGoogle().then((FirebaseUser user){
print(user);
}).catchError((onError){
print(onError);
});
}
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: RaisedButton(
color: Color(0xFF448AFF),
textColor: Color(0xFFFFFFFF),
child: Text('Login'),
onPressed: signIn,
),
),
]),
Padding(
padding:
EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: FlatButton(
textColor: Color(0xFF448AFF),
child: Text('Forgot Password'),
onPressed: () {
print('onPressed');
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(50, 70, 0, 10),
child: Text(
'Still do not have an account ',
style: TextStyle(color: Color(0xFF9E9E9E)),
),
),
Padding(
padding: EdgeInsets.fromLTRB(0, 70, 30, 10),
child: FlatButton(
textColor: Color(0xFF448AFF),
child: Text('registration'),
onPressed: () {
Navigator.of(context).pushNamedAndRemoveUntil(
'/registration', (Route<dynamic> route) => false);
},
),
),
],
),
],
),
),
),
]),
);
break;
case LoginStatus.signIn:
return HomeScreen();
break;
}
}
Future<void> signIn() async {
final formState = _formKey.currentState;
if(formState.validate()) {
setState(() {
_loginStatus = LoginStatus.signIn;
formState.save();
});
try {
FirebaseUser user = await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password);
}catch(e){
print(e.message);
}
}
}
}
after looking at your code i think i see where the problem is. The way i have understood your code is that the method 'safePref' is called to save password and email to shared preferences. Also, i hope its true that the method to get from shared preferences is 'getPref'. The error comes in that the value stored is a String
preferences.setString('email', _email);
preferences.setString('password', _password);
and the value read from storage is expected to be an Integer
value = preferences.getInt('password');
value = preferences.getInt('email');
You should change the last two to be
value = preferences.getString('password');
value = preferences.getString('email');
since the value stored is a String. To compare the Strings against integers you can change the statement
_loginStatus = value == 1 ? LoginStatus.signIn :LoginStatus.notSignIn;
to be
_loginStatus = int.parse(value) == 1 ? LoginStatus.signIn :LoginStatus.notSignIn;
My solution should solve the String problem but i think it will always return a false unless the Users Password is '1'.
Hope this helps. Thanks.
You have as String value and try to read as int value here's the problem . You should first read as String your email and password and then parse them to int.
var value;
getPref()async{
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
value = preferences.getString('password');
value = preferences.getString('email');
_loginStatus = int.parse(value) == 1 ? LoginStatus.signIn :LoginStatus.notSignIn;
});
}

Flutter code, accept value from user display required field

**Hello, I am developing an app in which the user should enter the integer values.according to that values we should display those number of text fields..
for Example:
1) enter total number of subject=10;
2) click on the button;
3) After button is clicked should display 10 text fields;
4) I have no idea what to do so if you know then help me plz.**
import 'package:flutter/material.dart';
class imcaaddsubject extends StatefulWidget {
#override
_imcaaddsubjectState createState() => _imcaaddsubjectState();
}
class _imcaaddsubjectState extends State<imcaaddsubject> {
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(5),
child: Card(
child: ListView(
padding: EdgeInsets.all(10),
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10),
),
new TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(style: BorderStyle.solid)),
labelText: "NUMBER OF SUBJECTS",
hintText: "Enter number of subjects",
),keyboardType: TextInputType.number,
),
Padding(
padding: EdgeInsets.only(top: 15),
),
new RaisedButton(
child: Text(
"OK",
style:
TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
color: Colors.cyan,
onPressed: () {},
)
],
),
),
);
}
}
You can try like this :
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: MyApp(),
));
class MyApp extends StatefulWidget {
#override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
int numberOfSubjects = 0;
Widget subjectsBuilder(int numberOfSubjects) {
if (numberOfSubjects > 0) {
return ListView.builder(
itemBuilder: (BuildContext context, numberOfSubjects) {
return TextField(
decoration: InputDecoration(hintText: "enter a text"),
);
},
itemCount: numberOfSubjects,
);
} else {
return SizedBox();
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Card(
child: ListView(
padding: EdgeInsets.all(10),
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10),
),
new TextField(
onSubmitted: (String value) {
setState(() {
numberOfSubjects = int.parse(value);
});
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(style: BorderStyle.solid)),
labelText: "NUMBER OF SUBJECTS",
hintText: "Enter number of subjects",
),
keyboardType: TextInputType.number,
),
Padding(
padding: EdgeInsets.only(top: 15),
),
],
),
),
),
),
Expanded(
child: subjectsBuilder(numberOfSubjects),
)
]),
);
}
}
this code will display a number of text fields according to user input below the first text field , of course you can render it in a new page .. also you don't have to use a button , it's enough to user submit text .

Resources