Flutter General dialog box - set state not working - flutter

I have an issue with my General Dialog Box. I would like to display a star. Then I would like to change it state when the star is taped and replace the icon by a yellow Star.
But is does not work. The Dialog Box is not refreshed so the icon is not changing. Please, can you look at the source code below and point me into the right direction please?
Many thanks.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:date_time_picker/date_time_picker.dart';
import 'package:gtd_official_sharped_focused/snackbar.dart';
String _isImportantInboxTask ;
String _isUrgentInboxTask ;
String inboxTaskDisplayed;
String isImportant = "false" ;
String isUrgent = "false" ;
String myProjectName ;
var taskSelectedID;
//---------------
//String _initialValue;
//_-----------------
var documentID;
var textController = TextEditingController();
var popUpTextController = TextEditingController();
class Inbox extends StatefulWidget {
Inbox({Key key}) : super(key: key);
#override
_InboxState createState() => _InboxState();
}
class _InboxState extends State<Inbox> {
GlobalKey<FormState> _captureFormKey = GlobalKey<FormState>();
bool isOn = true;
#override
Widget build(BuildContext context) {
void showAddNote() {
TextEditingController _noteField = new TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return CustomAlertDialog(
content: Container(
width: MediaQuery.of(context).size.width / 1.3,
height: MediaQuery.of(context).size.height / 4,
child: Column(
children: [
TextField(
controller: _noteField,
maxLines: 4,
decoration: InputDecoration(
border: const OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.black, width: 1.0),
),
),
),
SizedBox(height: 10),
Material(
elevation: 5.0,
borderRadius: BorderRadius.circular(25.0),
color: Colors.white,
child: MaterialButton(
minWidth: MediaQuery.of(context).size.width / 1.5,
onPressed: () {
Navigator.of(context).pop();
CollectionReference users = FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('allTasks');
users
.add({'task_Name': _noteField.text,'task_Status': 'Inbox' })
.then((value) => print("User Document Added"))
.catchError((error) =>
print("Failed to add user: $error"));
},
padding: EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 15.0),
child: Text(
'Add Note',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
),
);
});
}
return Scaffold(
appBar: new AppBar(
title: new Text('Inbox Page'),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.add_circle_outline,
color: Colors.white,
),
onPressed: () {
showAddNote();
// do something
},
),
],
),
drawer: MyMenu(),
backgroundColor: Colors.white,
body: Column(
//mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: MediaQuery.of(context).size.height / 1.4,
width: MediaQuery.of(context).size.width,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('allTasks')
.where('task_Status', isEqualTo: 'Inbox')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: snapshot.data.docs.map((document) {
return Wrap(
children: [Card(
child: SwipeActionCell(
key: ObjectKey(document.data()['task_Name']),
actions: <SwipeAction>[
SwipeAction(
title: "delete",
onTap: (CompletionHandler handler) {
CollectionReference users = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('allTasks');
users
.doc(document.id)
.delete()
.then((value) => print("Note Deleted"))
.catchError((error) => print(
"Failed to delete Task: $error"));
},
color: Colors.red),
],
child: Padding(
padding: const EdgeInsets.all(0.0),
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
minWidth: leadingIconMinSize,
minHeight: leadingIconMinSize,
maxWidth: leadingIconMaxSize,
maxHeight: leadingIconMaxSize,
),
child: Image.asset('assets/icons/inbox.png'),
),
title: GestureDetector(
child: Text(
//'task_Name' correspond au nom du champ dans la table
document.data()['task_Name'],
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
// Pour editer task
onDoubleTap: (){
taskSelectedID = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('allTasks')
.doc(document.id);
//Dialog
return showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: MaterialLocalizations.of(context)
.modalBarrierDismissLabel,
barrierColor: Colors.black45,
transitionDuration: const Duration(milliseconds: 20),
pageBuilder: (BuildContext buildContext,
Animation animation,
Animation secondaryAnimation) {
return Scaffold(
appBar: AppBar(
title: Text ('Edit Task'),
leading: InkWell(
child: Icon(Icons.close),
onTap:(){Navigator.of(context).pop();}
),
actions: [Padding(
padding: const EdgeInsets.fromLTRB(0, 0,16.0,0),
child: InkWell(
child: Icon(Icons.save),
onTap: () {
final loFormInbox = _captureFormKey
.currentState;
if (loFormInbox.validate()) {
loFormInbox.save();
CollectionReference users = FirebaseFirestore
.instance
.collection(
'Users')
.doc(FirebaseAuth
.instance
.currentUser.uid)
.collection(
'allTasks');
users
.add({
'task_Name': _valueTaskNameSaved,
})
.then((value) =>
print(
"Task Created"))
.catchError((
error) =>
print(
"Failed to add task: $error"));
showSimpleFlushbar(
context,
'Task Saved',
_valueTaskNameSaved,
Icons
.mode_comment);
loFormInbox.reset();
isImportant = 'false';
isUrgent = 'false';
}
}
),
)],
),
body: 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: [
Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
child: TextFormField(
initialValue: document.data()['task_Name'],
decoration: InputDecoration(hintText: "Task Name"),
maxLength: 70,
maxLines: 2,
onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
validator: (valProjectName) {
setState(() => _valueTaskNameToValidate = valProjectName);
return valProjectName.isEmpty? "Task name cannot be empty" : null;
},
onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
),
)),
//Test Energy et Time / Important /urgent
Material(
child:
Container(
// color: Colors.red,
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children:[
//Important
FlatButton(
child:
InkWell(
child: Container(
// color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
isImportant =="true" ? Icon(Icons.star,color: Colors.orange,) :
Icon(Icons.star_border, color: Colors.grey,),
// Icon(Icons.battery_charging_full),
Text('Important'),
],
)
),
onTap: () {
setState(() {
if (isImportant=='true'){
isImportant = 'false';}
else
{isImportant= 'true';
}
});
},
),
),
RaisedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Close",
style: TextStyle(color: Colors.white),
),
color: const Color(0xFF1BC0C5),
)
//++++++++++++++++
],
),
),
),
);
});
},
),
),
),
),
),
),
]
);
}).toList(),
);
}),
),
],
),
bottomNavigationBar: MyBottomAppBar(), //PersistentBottomNavBar(),
);
}
}
#override
Widget build(BuildContext context){
return _widget();
}
}
Thanks to your solution, I am able to do what I was willing to do. But now, I have an other issue. In the version 1 of my code, I am using this code
Theme(
data: ThemeData(
inputDecorationTheme: InputDecorationTheme(
border: InputBorder.none,
)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
child: TextFormField(
initialValue: document.data()['task_Name'],
decoration: InputDecoration(hintText: "Task Name"),
maxLength: 70,
maxLines: 2,
onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
validator: (valProjectName) {
setState(() => _valueTaskNameToValidate = valProjectName);
return valProjectName.isEmpty? "Task name cannot be empty" : null;
},
onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
),
)),
This part was working well. But after the modifications, I am getting an error. The error is about document.
Undefined name 'document'. Try correcting the name to one that is defined, or defining the name.
Please, can you help me with this so I can finalize this page. Thank you

So you want to change the color of icon on clicking it inside dialogBox,
but unfortunately you are using stateless widget Scaffold in return of showGeneralDialog builder so one thing that can possibly help is to make a separate StateFull Widget RatingDialogBox and use that in the builder.
Also instead of InkWell you can use IconButton

I will suggest you to use this package it is great
flutter_rating_bar
also feel free to comment is this doesn't satisfy your need

Related

when dialog open and after close dialog when focus on textFormField widget rebuild unnecessarily and user doesn't able to put text in this

When I click on the update profile button I want to show a dialog if no changes are found, but when I close this and try to change the username or email again the entire widget rebuilds twice as soon as I focus on the TextFormField.
import 'dart:developer';
import 'package:chatappwithfirebase/Screens/profilescreen.dart';
import 'package:chatappwithfirebase/api/customtranscation.dart';
import 'package:chatappwithfirebase/widgets/imagepick.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../Screens/mainscreen.dart';
import '../utils/utils.dart';
class EditProfile extends StatefulWidget {
EditProfile({Key? key,required this.initialValues}) : super(key: key);
final Map<String,String> initialValues;
#override
State<EditProfile> createState() => _EditProfileState();
}
class _EditProfileState extends State<EditProfile> {
final _fromKey = GlobalKey<FormState>();
final firebase =FirebaseFirestore.instance.collection('users');
final firebaseAuth =FirebaseAuth.instance;
TextEditingController? txtEmail;
TextEditingController? txtUsername;
var updatedProfileImageLink;
File? selectedImage;
#override
void initState() {
txtEmail =TextEditingController(text: widget.initialValues['emailAddress']);
txtUsername =TextEditingController(text: widget.initialValues['username']);
super.initState();
}
void getImage(ImageSource imageSource)async{
ImagePicker picker =ImagePicker();
Navigator.of(context).pop();
var getImage= await picker.pickImage(source: imageSource);
selectedImage = await File(getImage!.path);
print(selectedImage!.path);
}
void updateProfile()async{
FocusScope.of(context).unfocus();
if(
widget.initialValues['imageUrl'] != updatedProfileImageLink && selectedImage != null ||
widget.initialValues['emailAddress'] != txtEmail!.text ||
widget.initialValues['username'] != txtUsername!.text)
{
if (widget.initialValues['imageUrl'] != updatedProfileImageLink && selectedImage != null) {
showDialog(
barrierDismissible: false,
context: context, builder: (context){
return AlertDialog(
content: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(width: 5,),
Text('Uploading...')
],
),
);
}).then((value) => setState((){}));
final storage =FirebaseStorage.instance.ref().child('User_image').child(firebaseAuth.currentUser!.uid +'.jpg');
await storage.putFile(selectedImage!);
updatedProfileImageLink = await storage.getDownloadURL();
await firebase.doc(firebaseAuth.currentUser!.uid).update({
'imageUrl': updatedProfileImageLink}).then((value) => Navigator.of(context).pop());
}
if (widget.initialValues['emailAddress'] != txtEmail!.text) {
final userdata = await firebase.doc(firebaseAuth.currentUser!.uid).get();
await firebaseAuth.signInWithEmailAndPassword(
email: userdata['email'], password: userdata['password']);
await FirebaseAuth.instance.currentUser!.updateEmail(txtEmail!.text);
await firebase.doc(firebaseAuth.currentUser!.uid).update({
'email': txtEmail!.text}).then((value) => showDialog(
context: context,
builder: (context){
return CupertinoAlertDialog(
title: CircleAvatar(
backgroundColor: Colors.green,
child: Icon(Icons.done,color: Colors.white,size: 30,)),
content: Text('Email Address Updated'),
actions: [
CupertinoDialogAction(
onPressed: (){
widget.initialValues['emailAddress'] =txtUsername!.text;
Navigator.of(context).pop();
},
child: Text('Ok')
)
],
);
}));
}
if (widget.initialValues['username'] != txtUsername!.text) {
await firebase.doc(firebaseAuth.currentUser!.uid).update({
'username': txtUsername!.text}).then((value) => showDialog(
context: context,
builder: (context){
return CupertinoAlertDialog(
title: CircleAvatar(
backgroundColor: Colors.green,
child: Icon(Icons.done,color: Colors.white,size: 30,)),
content: Text('Username Updated'),
actions: [
CupertinoDialogAction(
onPressed: (){
widget.initialValues['username'] =txtUsername!.text;
Navigator.of(context).pop();
},
child: Text('ok')
),
],
);
})
);
}
}
else{
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: const Text('Alert'),
content: const Text('Changes Not Found'),
// actions: <CupertinoDialogAction>[
// CupertinoDialogAction(
// //isDefaultAction: true,
// onPressed: () {
// Navigator.pop(context);
// },
// child: const Text('ok'),
// ),
// ],
),
);
}
}
void _showImagePickOptions(context){
showModalBottomSheet(
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft :Radius.circular(20),topRight:Radius.circular(20) )),
context: context,
builder: (context){
return Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
onTap:() => getImage(ImageSource.camera),
leading: const Icon(Icons.camera_enhance,color: Colors.pink,),
title: const Text('Capture Image',style: TextStyle(color: Colors.grey),),
),
ListTile(
onTap:() => getImage(ImageSource.gallery),
leading: const Icon(Icons.image_sharp,color: Colors.purple,),
title: const Text('Select Image',style: TextStyle(color: Colors.grey),)
)
],
),
);
});
}
#override
Widget build(BuildContext context) {
log('loaded');
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.white,
elevation: 0,
title: Text('Edit Profile',style: TextStyle(color: Colors.black),),
leading: IconButton(onPressed: (){
Navigator.of(context).pop();
},icon: Icon(CupertinoIcons.back,color: iconColor,),),
actions: [
const Icon(Icons.more_vert,color: Colors.black,)
],
),
body: FutureBuilder(
future: firebase.doc(FirebaseAuth.instance.currentUser!.uid).get(),
builder: (context,userdata){
if(userdata.connectionState ==ConnectionState.waiting){
return Center(child: CircularProgressIndicator(color: accentColor,));
}
return Padding(
padding: EdgeInsets.all(20),
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: EdgeInsets.all(20),
child: Stack(
alignment: Alignment.bottomRight,
children: [
CircleAvatar(
radius: 60,
backgroundImage:updatedProfileImageLink == null ? NetworkImage(widget.initialValues['imageUrl']!) :
NetworkImage(updatedProfileImageLink)
),
CircleAvatar(
backgroundColor: accentColor,
child: IconButton(onPressed:()=> _showImagePickOptions(context),icon: Icon(Icons.camera_enhance,color: Colors.white,
),
),
)
]
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.04 ,),
Form(
key: _fromKey,
child: Column(
children: [
TextFormField(
controller: txtEmail,
decoration: InputDecoration(
prefixIcon: Icon(Icons.email),
label: Text('Email Address'),
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: accentColor)),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: iconColor))
),
),
SizedBox(height: MediaQuery.of(context).size.height * 0.02,),
TextFormField(
controller: txtUsername,
decoration: InputDecoration(
labelStyle: TextStyle(fontFamily: 'Roboto'),
prefixIcon: Icon(Icons.supervised_user_circle_rounded),
label: Text('Username'),
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: accentColor)),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: iconColor))
),
),
],
)),
SizedBox(height: MediaQuery.of(context).size.height * 0.03,),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: accentColor,
fixedSize: Size(200, 50)
),
onPressed: updateProfile,
child: Text('Update Profile'),),
],
),
),
);
}),
);
}
}
It works fine if I don't open a dialog, but when I do this problem shows up again.

Flutter & Firebase Error displaying an document (Array) from firebase on a view

I am using FireBase to store some data. So far, I was creating several collections.
But, I have understood that more collections I have more Firebase will cost when the application will be in production. Someone told me that I should create a 'General' collection, where I can store several documents in array. I just want to display on several cards, all the contexts of the array "context_Name"
So I have modify my collections and document, but I do not know how to get the same results as before I modify my code.
The error I am getting is type 'List' is not a subtype of type 'String'.
When the exception was thrown, this was the stack:
#0 _Context_List_Sate.build.. (package:lt/Views/Lists/14_contexts_lists_page.dart:217:45)
#1 MappedListIterable.elementAt (dart:_internal/iterable.dart:412:31)
#2 ListIterator.moveNext (dart:_internal/iterable.dart:341:26)
#3 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:188:27)
#4 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
If i understand the error, I do not find how to fix that while displaying all the records, but one by one on a card. Many thanks for your help.
class Context_List_View extends StatefulWidget {
Context_List_View({Key key}) : super(key: key);
#override
_Context_List_Sate createState() => _Context_List_Sate();
}
class _Context_List_Sate extends State<Context_List_View> {
#override
Widget build(BuildContext context) {
void showAddNote() {
TextEditingController _noteField = new TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return CustomAlertDialog(
content: Container(
width: MediaQuery.of(context).size.width / 1.3,
height: MediaQuery.of(context).size.height / 4,
child: Column(
children: [
TextField(
controller: _noteField,
maxLines: 4,
decoration: InputDecoration(
border: const OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.black, width: 1.0),
),
),
),
SizedBox(height: 10),
Material(
elevation: 5.0,
borderRadius: BorderRadius.circular(25.0),
color: Colors.white,
child: MaterialButton(
minWidth: MediaQuery.of(context).size.width / 1.5,
onPressed: () {
Navigator.of(context).pop();
CollectionReference users = FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('general');
users
.add({'context_Name': _noteField.text,})
.then((value) => print("User Document Added"))
.catchError((error) =>
print("Failed to add user: $error"));
},
padding: EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 15.0),
child: Text(
'Add Context',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
)
],
),
),
);
});
}
return Scaffold(
appBar: new AppBar(
title: new Text('Contexts'),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.add_circle_outline,
color: Colors.white,
),
onPressed: () {
showAddNote();
},
),
],
),
drawer: MyMenu(),
backgroundColor: Colors.white,
body: Column(
children: [
Container(
height: MediaQuery.of(context).size.height /1.4,
width: MediaQuery.of(context).size.width,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('general')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children: snapshot.data.docs.map((document) {
return Wrap(
children: [Card(
child: SwipeActionCell(
key: ObjectKey(document['context_Name']),
trailingActions: <SwipeAction>[
SwipeAction(
title: "delete",
onTap: (CompletionHandler handler) {
CollectionReference users = FirebaseFirestore
.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('contexts');
users
.doc(document.id)
.delete()
.then((value) => print("Context Deleted"))
.catchError((error) => print(
"Failed to delete Next Action: $error"));
},
color: Colors.red),
],
child: Padding(
padding: const EdgeInsets.all(0.0),
child: ListTile(
leading: ConstrainedBox(
constraints: BoxConstraints(
minWidth: leadingIconMinSize,
minHeight: leadingIconMinSize,
maxWidth: leadingIconMaxSize,
maxHeight: leadingIconMaxSize,
),
child: Image.asset('assets/icons/tag.png'),
),
trailing: IconButton(icon: Icon(Icons.edit), onPressed: ()
{
//EDIT CONTEXT
showDialog(
context: context,
barrierDismissible: true,
builder: (BuildContext context){
return AlertDialog(
title: Text("Edit Context"),
content:
TextFormField(
initialValue: document['context_Name'],
onChanged: (value) {
setState(() {
_newContextName = value;
});
},
),
actions: <Widget>[
FlatButton(
child: Text("OK"),
onPressed: (){
setState(() {
var contextRecordID = (document.id);
FirebaseFirestore.instance
.collection('Users')
.doc(
FirebaseAuth.instance.currentUser.uid)
.collection('general')
.doc(contextRecordID)
.update({
'context_Name':_newContextName,
});
});
Navigator.of(context).pop(true);
},
),//OK Button
FlatButton(
child: Text("Cancel"),
onPressed: (){
Navigator.of(context).pop(false);
},
),//Cancel Button
],
);
});}),
title: Text(
document['context_Name'],
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
),
),
),
]
);
}).toList(),
);
}),
),
],
),
// bottomNavigationBar: ,
);
}
}
You need to iterate over the members of the context_Name field instead of iterating over the entire general collection. Change the beginning of the StreamBuilder to the following:
// ... other code
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser.uid)
.collection('general')
.doc('baceZyyYUciEGGADfgOv')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView(
children:
(snapshot.data.get('context_Name') as List<String>)
.map((contextName) {
return Wrap(children: [
Card(
child: SwipeActionCell(
key: ObjectKey(contextName),
// ... other code
You will also have to update the callbacks to the SwipeActions and AlertDialog as the document variable will no longer exists. Also, change
title: Text(
document['context_Name'],
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
to
title: Text(
contextName,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
(towards the end of the code).

How to fix when BackdropScaffold frontLayer's elements doesn't appear?

Sorry for the bad title:(!
My app should show in the home screen cards and FloatingActionButton, I've created the cards in separate file, so I'm forwarding the data to it, also to store my data I'm using sqlite which I'm new to it..
the FloatingActionButton should appear when I run the application, and I need it to add new cards. I know that the database is empty now, but why the FloatingActionButton is not appearing?
when running it it looks like this.
I had followed a tutorial in the part when using the sqlite, and this is a part of my homeScreen code :
frontLayer: FutureBuilder<List<Reminder>>(
future: _reminders,
builder: (context, snapshot) {
if (snapshot.hasData) {
_currentReminders = snapshot.data!;
return ListView(children: [
...snapshot.data!.map<Widget>((reminder) {
return ReminderCard(
name: reminder.name, details: reminder.details);
}).followedBy([
Scaffold(
backgroundColor: Colors.amber,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black,
child: Icon(Icons.add),
onPressed: () {},
),
)
]).toList(),
Padding(
padding: const EdgeInsets.all(8.0),
),
Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black,
child: Icon(Icons.add),
onPressed: () {}
this is the full code if I didn't paste the right part of my code: https://github.com/RarLasebai/reminder3/blob/main/lib/ui/Screens/homeScreen.dart
i have cloned your project and did a little changes on the HomeScreen
here is how u should do it
import 'package:flutter/material.dart';
import 'package:backdrop/backdrop.dart';
import 'package:untitled/helper.dart';
import 'package:untitled/models/reminder.dart';
import 'package:untitled/ui/widgets/ReminderCard.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
TextEditingController nameController = TextEditingController();
TextEditingController detailsController = TextEditingController();
final _formKey = GlobalKey<FormState>();
late ReminderCard card;
RHelper helper = RHelper();
late Future<List<Reminder>> _reminders;
late List<Reminder> _currentReminders;
//-------------------------Functions----------------
bool status = true;
#override
void initState() {
super.initState();
helper.initializeDatabase().then((value) => {print("------------donne?")});
_loadReminders();
}
void _loadReminders() {
_reminders = helper.getReminders();
if (mounted) setState(() {});
}
//Screen and appBar frontend
#override
Widget build(BuildContext context) {
return BackdropScaffold(
backgroundColor: Colors.white,
appBar: BackdropAppBar(
centerTitle: true,
title: (Text(
'قائمة التذكيرات',
style: Theme.of(context).textTheme.headline1,
)),
),
headerHeight: 110.0,
frontLayer: FutureBuilder<List<Reminder>>(
future: _reminders,
builder: (context, snapshot) {
if (snapshot.hasData) {
_currentReminders = snapshot.data!;
return ListView(children: [
Column(
children: _currentReminders.map<Widget>((reminder) {
return ReminderCard(
name: reminder.name, details: reminder.details);
}).toList(),
),
Padding(
padding: const EdgeInsets.all(8.0),
),
]);
}
return Center(child: Text("Loading>>.."));
},
),
backLayer: BackdropNavigationBackLayer(
items: [
ListTile(
leading: ImageIcon(AssetImage('icons/to-do-list.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("التذكيرات",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('home');
}),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/athkar.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("الأذكار",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('athkar');
}),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/mosque.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("مواقيت الصلاة",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('adhan');
},
),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/Tasbeeh.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("تسبيح",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('tasbeeh');
},
),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/quran.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("مصحف",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('moshaf');
},
),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/tadabur.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("وقفات تدبرية ",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('tadabur');
}),
Divider(),
ListTile(
leading: ImageIcon(AssetImage('icons/information.png')),
title: Align(
alignment: Alignment.centerRight,
child: Text("تواصل معنا",
style: Theme.of(context).textTheme.bodyText2)),
onTap: () {
Navigator.of(context).pushReplacementNamed('contact');
})
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
showModalBottomSheet(
useRootNavigator: true,
context: context,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(24),
),
),
builder: (context) {
return StatefulBuilder(
builder: (context, setModalState) {
return Container(
padding: const EdgeInsets.all(32),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (String? value) {
if (value!.isEmpty)
return 'Please enter name';
},
controller: detailsController,
style: TextStyle(
color: Colors.black, fontSize: 15.0),
decoration: InputDecoration(
errorStyle: TextStyle(
color: Colors.red, fontSize: 15.0),
labelText: 'اسم التذكير',
labelStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(5.0)),
),
),
SizedBox(
height: 10,
),
TextFormField(
controller: nameController,
style: TextStyle(
color: Colors.black, fontSize: 15.0),
decoration: InputDecoration(
labelText: 'التفاصيل',
labelStyle: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
border: OutlineInputBorder(
borderRadius:
BorderRadius.circular(5.0)),
),
),
SizedBox(
height: 10,
),
ElevatedButton(
onPressed: () {
setState(() {
if (_formKey.currentState!
.validate()) {
_save();
Navigator.pop(context);
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(
content: Text(
'تم حفظ التذكير')));
}
});
},
child: Text('حفظ'),
)
],
),
),
);
});
},
);
})
);
}
void _save() {
var _reminder = Reminder(
name: nameController.text, details: detailsController.text, save: 0);
helper.insertReminder(_reminder);
_loadReminders();
}
}
and for a athkar project i really suggest that you use provider or riverpod , or any kind of state management

Why am I having memory issues with flutter ChangeNotifierProvider?

I am making a shopping cart app in flutter with Change Notifier Provider. It is working fast and well at first. But it takes the more memory, the more I use it. I am adding and removing clearing items from list. Nothing complicated. Cannot know why it is working like this. It is slowing down gradually. This is main.dart:
class Main extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => Cart(),
child: MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: swatchColor,
primaryColor: primaryColor,
accentColor: tertiaryColor,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.black,
selectionColor: primaryColor,
selectionHandleColor: primaryColor,
),
),
initialRoute: '/login',
routes: {
'/home': (context) => Home(),
'/login': (context) => Login(),
'/tableReview': (context) => TableReview(),
'/createOrder': (context) => CreateOrder(),
'/orderReview': (context) => OrderReview(),
},
),
);
}
}
This is main cart_model.dart
import 'package:counter/data/models/cart_item.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
class Cart extends ChangeNotifier {
List<Item> cart = [];
addItemToCart({#required item}) {
Item newItem = Item(
id: item.id,
price: item.price is int ? item.price : int.parse(item.price),
title: item.title,
);
int i = cart.indexWhere((previousItem) => previousItem.id == newItem.id);
if (i > -1) {
cart[i].count++;
} else {
cart.add(newItem);
}
notifyListeners();
}
removeItemFromCart({#required item}) {
int index = cart.indexWhere((element) => element.id == item.id);
if (index > -1) {
if (cart[index].count > 1) {
cart[index].count--;
} else {
cart.removeWhere((element) => element.id == item.id);
}
}
notifyListeners();
}
clearCart() {
cart.clear();
notifyListeners();
}
int get totalPrice =>
cart.fold(0, (total, current) => total + (current.price * current.count));
}
This is menuitem.dart
class MenuItem extends StatelessWidget {
final dynamic foodItem;
MenuItem({#required this.foodItem});
void _showSecondPage(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (ctx) => Scaffold(
backgroundColor: Colors.black45,
body: Center(
child: Hero(
tag: foodItem.imgPath,
child: Image(image: NetworkImage(base_url + foodItem.imgPath)),
),
),
),
),
);
}
#override
Widget build(BuildContext context) {
int itemIndex = Provider.of<Cart>(context, listen: false)
.cart
.indexWhere((item) => item.id == foodItem.id);
return Container(
height: 80,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: () => _showSecondPage(context),
child: Hero(
tag: foodItem.imgPath,
child: CircleAvatar(
backgroundImage: NetworkImage(base_url + foodItem.imgPath),
),
),
),
SizedBox(
width: 15,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
foodItem.title,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 17,
),
),
Text('${foodItem.price.toString()} сум'),
],
)
],
),
Container(
width: 160,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon:
Icon(Icons.remove, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
Text(
itemIndex > -1
? '${Provider.of<Cart>(context).cart[itemIndex].count}'
: '0',
style: TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(Icons.add, color: Theme.of(context).primaryColor),
onPressed: () {
Provider.of<Cart>(context, listen: false)
.addItemToCart(item: foodItem);
},
),
],
),
),
],
),
);
}
}
This is consumer part:
import 'package:counter/common/socketio.dart';
import 'package:counter/data/models/cart_model.dart';
import 'package:counter/presentation/widgets/empty_cart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class OrderReview extends StatefulWidget {
#override
_OrderReviewState createState() => _OrderReviewState();
}
class _OrderReviewState extends State<OrderReview> {
bool isCommentEnabled = false;
String guestCount;
String comment = '';
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
final myCart = context.watch<Cart>();
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
title: Text('Проверка заказа'),
),
body: Builder(
builder: (context) {
if (myCart.cart.length > 0) {
handleOrderCreate() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String userId = prefs.getString('userId');
String tableNum = prefs.getString('tableNum');
String status = 'accepted';
print('$userId, $tableNum, $status');
Map orderToCreate = {
'tableNum': tableNum,
'status': 'accepted',
'userId': userId,
'guestCount': guestCount,
'comment': comment,
'foodList': myCart.cart
};
socketIO.emit('createOrder', json.encode(orderToCreate));
Navigator.of(context).pushNamed('/home');
Provider.of<Cart>(context, listen: false).clearCart();
}
return GestureDetector(
onTap: () => FocusScope.of(context).requestFocus(new FocusNode()),
child: LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: IntrinsicHeight(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Form(
key: _formKey,
child: Column(
children: [
Container(
height: 350,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
boxShadow: [
BoxShadow(
color:
Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0,
3), // changes position of shadow
),
]),
child: ListView.separated(
itemBuilder:
(BuildContext context, int i) {
return ListTile(
title: Text(myCart.cart[i].title),
trailing: Container(
width: 160,
child: Row(
crossAxisAlignment:
CrossAxisAlignment.center,
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.remove,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.removeItemFromCart(
item: myCart
.cart[i]);
},
),
Text(
'${myCart.cart[i].count}',
style:
TextStyle(fontSize: 18),
),
IconButton(
icon: Icon(
Icons.add,
color: Theme.of(context)
.primaryColor,
),
onPressed: () {
Provider.of<Cart>(context,
listen: false)
.addItemToCart(
item: myCart
.cart[i]);
},
),
],
),
),
);
},
separatorBuilder:
(BuildContext context, int) {
return Divider(
height: 2,
color: Colors.grey,
);
},
itemCount: myCart.cart.length,
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Количество гостей',
),
onChanged: (newValue) {
setState(() => guestCount = newValue);
},
validator: (value) {
if (value == null || value.isEmpty) {
return 'Пожалуйста, введите количество гостей!';
}
return null;
},
),
),
SizedBox(height: 20),
Container(
child: TextFormField(
onChanged: (newValue) {
setState(() => comment = newValue);
},
enabled: isCommentEnabled,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText:
'Лаваш острый, хот дог без майонеза и т.д.',
// labelText: 'Комментарий',
),
maxLines: 2,
),
),
Row(
children: [
Text('Комментарий'),
Switch(
value: isCommentEnabled,
onChanged: (bool value) {
setState(() =>
this.isCommentEnabled = value);
},
),
],
)
],
),
),
SizedBox(height: 20),
Row(
children: [
Text(
'Общая цена: ',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
SizedBox(width: 20),
Text(
'${myCart.totalPrice} сум',
style: TextStyle(fontSize: 18),
),
],
),
Container(
height: 50,
width: 170,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.resolveWith(
(states) =>
Theme.of(context).primaryColor),
),
onPressed: () {
if (_formKey.currentState.validate()) {
handleOrderCreate();
}
},
child: Text(
'Отправить',
style: TextStyle(
color: Colors.white, fontSize: 18),
),
),
),
],
),
),
),
),
);
},
),
);
} else {
print('111');
return EmptyCart();
}
},
),
);
}
}
Is there something wrong with my code?

Flutter: The method '/' was called on null. Receiver: null Tried calling: /(1080.0)

I'm getting this error since I've used Media Query for setting up Responsive UI. Below is the error that I'm getting in the terminal.
I don't know which method calling is returning null according to Dart. Because I'm navigating to new Screen via Raised Button and it is showing this error on Constructor of Widget/Class that I called on onPressed of the button
Here is the code of my class from where I'm navigating to new Screen of Doctor's Login:
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:medkit/animations/fadeAnimation.dart';
import 'package:medkit/animations/bottomAnimation.dart';
import 'package:medkit/doctor/doctorLogin.dart';
import 'package:medkit/doctor/doctorPanel.dart';
import 'aboutUs.dart';
class UserType extends StatelessWidget {
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
Future<bool> _onWillPop() async {
return (await showDialog(
context: context,
builder: (context) => new AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)
),
title: new Text(
"Exit Application",
style: TextStyle(fontWeight: FontWeight.bold),
),
content: new Text("Are You Sure?"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
FlatButton(
shape: StadiumBorder(),
color: Colors.white,
child: new Text(
"Close",
style: TextStyle(color: Colors.blue),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
shape: StadiumBorder(),
color: Colors.white,
child: new Text(
"Yes",
style: TextStyle(color: Colors.red),
),
onPressed: () {
exit(0);
},
),
],
),
)) ??
false;
}
return WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
body: SafeArea(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: width * 0.04),
child: Column(
children: <Widget>[
SizedBox(
height: height * 0.08,
),
FadeAnimation(
0.3,
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Category',
style: TextStyle(color: Colors.black, fontSize: 30),
),
GestureDetector(
onTap: () => _exitAlert(context),
child: Icon(
Icons.exit_to_app,
size: height * 0.04,
),
)
],
),
),
SizedBox(height: height * 0.09),
Column(
children: <Widget>[
FadeAnimation(
0.4,
CircleAvatar(
backgroundColor: Colors.black.withOpacity(0.2),
radius: height * 0.075,
child: Image(image: AssetImage("assets/doctor.png")),
),
),
WidgetAnimator(patDocBtn('Doctor', context)),
SizedBox(
height: height * 0.1,
),
FadeAnimation(
0.4,
CircleAvatar(
backgroundColor: Colors.black.withOpacity(0.2),
radius: height * 0.075,
child: Image(image: AssetImage("assets/patient.png")),
),
),
WidgetAnimator(patDocBtn('Patient', context)),
SizedBox(height: height * 0.13,),
GestureDetector(
onTap: () => Navigator.push(context, new MaterialPageRoute(builder: (context) => AboutUs())),
child: Column(
children: <Widget>[
Text('Version', style: TextStyle(fontWeight: FontWeight.bold),),
Text('V 0.1', style: TextStyle(fontSize: 12),)
],
),
),
SizedBox(height: 5,)
],
)
],
),
),
),
),
);
}
Widget patDocBtn(String categoryText, context) {
return Container(
width: MediaQuery.of(context).size.width * 0.5,
child: RaisedButton(
onPressed: () {
if (categoryText == 'Doctor') {
Navigator.pushNamed(context, 'DoctorLogin');
} else {
Navigator.pushNamed(context, 'PatientLogin');
}
},
color: Colors.white,
child: Text("I am " + categoryText),
shape: StadiumBorder(),
),
);
}
_exitAlert(context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)
),
title: new Text(
"Exit Application",
style: TextStyle(fontWeight: FontWeight.bold),
),
content: new Text("Are You Sure?"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
FlatButton(
color: Colors.white,
child: new Text(
"Close",
style: TextStyle(color: Colors.blue),
),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
color: Colors.white,
child: new Text(
"Yes",
style: TextStyle(color: Colors.red),
),
onPressed: () {
exit(0);
},
),
],
);
},
);
}
}
And here is Doctor's Login class code
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:medkit/animations/fadeAnimation.dart';
import 'package:medkit/animations/bottomAnimation.dart';
import 'package:medkit/doctor/doctorPanel.dart';
import 'package:medkit/otherWidgetsAndScreen/backBtn.dart';
import 'package:medkit/otherWidgetsAndScreen/imageAvatar.dart';
import 'package:toast/toast.dart';
class DoctorLogin extends StatefulWidget {
#override
_DoctorLoginState createState() => _DoctorLoginState();
}
class _DoctorLoginState extends State<DoctorLogin> {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = new GoogleSignIn();
Future<FirebaseUser> _signIn(BuildContext context) async {
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
FirebaseUser userDetails =
await _firebaseAuth.signInWithCredential(credential);
ProviderDoctorDetails providerInfo =
new ProviderDoctorDetails(userDetails.providerId);
List<ProviderDoctorDetails> providerData =
new List<ProviderDoctorDetails>();
providerData.add(providerInfo);
DoctorDetails details = new DoctorDetails(
userDetails.providerId,
userDetails.displayName,
userDetails.photoUrl,
userDetails.email,
providerData,
);
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => DoctorPanel(
detailsUser: details,
)));
return userDetails;
}
#override
Widget build(BuildContext context) {
final nameTextFieldController = TextEditingController();
final nameTextField = TextField(
keyboardType: TextInputType.text,
autofocus: false,
maxLength: 30,
textInputAction: TextInputAction.next,
onSubmitted: (_) => FocusScope.of(context).nextFocus(),
controller: nameTextFieldController,
decoration: InputDecoration(
fillColor: Colors.black.withOpacity(0.07),
filled: true,
labelText: 'Enter Name',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(const Radius.circular(20)))),
);
final phNumberTextController = TextEditingController();
final phoneTextField = TextField(
keyboardType: TextInputType.phone,
autofocus: false,
maxLength: 11,
controller: phNumberTextController,
textInputAction: TextInputAction.next,
onSubmitted: (_) => FocusScope.of(context).nextFocus(),
decoration: InputDecoration(
filled: true,
fillColor: Colors.black.withOpacity(0.07),
labelText: 'Enter Number',
prefixIcon: Icon(Icons.phone),
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(const Radius.circular(20)),
),
),
);
final cnicTextController = TextEditingController();
final cnicTextField = TextFormField(
keyboardType: TextInputType.number,
autofocus: false,
maxLength: 13,
controller: cnicTextController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.black.withOpacity(0.07),
labelText: 'Enter CNIC',
prefixIcon: Icon(Icons.card_membership),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(20))),
);
final double width = MediaQuery.of(context).size.width;
final double height = MediaQuery.of(context).size.height;
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
resizeToAvoidBottomPadding: false,
body: SafeArea(
child: Container(
width: width,
height: height,
child: Stack(
children: <Widget>[
ImageAvatar(
assetImage: 'assets/bigDoc.png',
),
Container(
width: width,
height: height,
margin: EdgeInsets.fromLTRB(width * 0.03, 0, width * 0.03, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
BackBtn(),
SizedBox(height: height * 0.05,),
Text(
"\t\tLogin",
style: GoogleFonts.abel(
fontSize: ScreenUtil.instance.setSp(35),
fontWeight: FontWeight.bold),
),
SizedBox(
height: height * 0.05,
),
WidgetAnimator(nameTextField),
WidgetAnimator(phoneTextField),
WidgetAnimator(cnicTextField),
SizedBox(height: height * 0.01,),
FadeAnimation(
1.5,
SizedBox(
width: width,
height: height * 0.07,
child: RaisedButton(
color: Colors.white,
shape: StadiumBorder(),
onPressed: () {
if (nameTextFieldController.text != "" ||
phNumberTextController.text != "" ||
cnicTextController.text != "") {
Firestore.instance
.collection('doctorInfo')
.document(nameTextFieldController.text)
.setData({
'cnic': cnicTextController.text,
'phoneNumber': phNumberTextController.text,
});
_signIn(context)
.then((FirebaseUser user) =>
print('Gmail Logged In'))
.catchError((e) => print(e));
nameTextFieldController.clear();
cnicTextController.clear();
phNumberTextController.clear();
} else {
Toast.show('Fields Cannot be Empty!', context,
backgroundColor: Colors.red,
gravity: Toast.CENTER,
duration: Toast.LENGTH_SHORT);
}
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image(
image: AssetImage('assets/google.png'),
height: ScreenUtil.instance.setHeight(35),
),
SizedBox(width: ScreenUtil.instance.setWidth(15)),
Text(
'Login',
style: TextStyle(
letterSpacing: 2,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.instance.setSp(18)),
)
],
),
),
),
),
SizedBox(height: height * 0.02,),
FadeAnimation(
2,
Text(
'You Will be asked Question regarding your Qualifications!', textAlign: TextAlign.center,
style: TextStyle(color: Colors.black.withOpacity(0.5),),
),
),
],
),
),
],
),
),
)),
);
}
}
class DoctorDetails {
final String providerDetails;
final String userName;
final String photoUrl;
final String userEmail;
final List<ProviderDoctorDetails> providerData;
DoctorDetails(this.providerDetails, this.userName, this.photoUrl,
this.userEmail, this.providerData);
}
class ProviderDoctorDetails {
ProviderDoctorDetails(this.providerDetails);
final String providerDetails;
}
Solution
I was using Media Query along with a 3rd party dependency at same time. I just removed that Dependency and its use in my code and it solved
Conclusion
Probably you can't use Media Query along with third party dependency at same time for making your app responsive
Your pushNamed route, the route name starts with '/'? Did you declare it as '/NAMEOFTHEROUTE'?
If yes please use your pushNamed as'/NAMEOFTHEROUTE'.