TextField input won't print to console? - firebase

I'm trying to use a custom TextField widget in my AddNoteScreen. I don't know why it's not printing the TextField input or how to get it to work. I thought having the TextEditingController was all it needed.. I'm new.. sorry to post so much code I don't know how else to explain.
Here is my custom widget:
class MyWidget extends StatefulWidget {
final Widget textFields;
MyWidget(
{required this.textFields});
#override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
TextEditingController notesController = TextEditingController();
List<TextField> textFields = [];
#override
void initState() {
super.initState();
textFields.add(_buildTextField());
}
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
color: Colors.white,
),
height: 300,
alignment: Alignment.centerLeft,
child: ListView(
children: textFields,
),
);
}
TextField _buildTextField() {
return TextField(
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
decoration: InputDecoration(
prefix: Icon(
Icons.circle,
size: 10,
color: Colors.black,
),
prefixIconConstraints: BoxConstraints(
minWidth: 20,
minHeight: 10,
maxHeight: 10,
maxWidth: 20,
),
),
autofocus: true,
onSubmitted: (_) {
setState(() {
textFields.add(_buildTextField());
notesController.text + ' ';
});
}
);
}
}
My AddNoteScreen:
class AddNoteScreen extends StatefulWidget {
User user;
AddNoteScreen({
required this.user,
});
#override
State<AddNoteScreen> createState() => _AddNoteScreenState();
}
class _AddNoteScreenState extends State<AddNoteScreen> {
TextEditingController notesController = TextEditingController();
FirebaseFirestore firestore = FirebaseFirestore.instance;
bool loading = false;
#override
void initState(){
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor:Color (0xFF162242),
elevation: 0,
),
body: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
notesController.text = '';
},
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(20),
child: Column(children: [
Container(
padding: EdgeInsets.only(left: 10, right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10),),
color: Colors.white,
),
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
),
SizedBox(height: 50,),
loading ? Center (child: CircularProgressIndicator(),) : Container(
height: 50,
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: ()async{
if (
notesController.text.isEmpty)
{
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("All feilds are required")));
} else {
setState(() {
loading = true;
});
await FirestoreService().insertNote(notesController.text,
widget.user.uid);
CollectionReference notes = firestore.collection('notes');
QuerySnapshot allResults = await notes.get();
allResults.docs.forEach((DocumentSnapshot result) {
print(result.data());
});
setState(() {
loading = false;
});
Navigator.pop(context);
}
}, child: Text("Add Note", style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Color (0xFF162242)),
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
//color:Color (0xFF162242)
//ElevatedButton.styleFrom(primary: Color (0xFF162242),),
),
),
]),),
),
),
);
My FirestoreService page:
class FirestoreService{
FirebaseFirestore firestore = FirebaseFirestore.instance;
Future insertNote(String notes, String userId)async{
try{
await firestore.collection('notes').add({
"notes":notes,
"userId":userId
});
} catch(e){
}
}
}
And my NoteModel Screen:
class NoteModelEdit {
String id;
String notes;
String userId;
NoteModelEdit({
required this.id,
required this.notes,
required this.userId
});
factory NoteModelEdit.fromJson(DocumentSnapshot snapshot){
return NoteModelEdit(
id: snapshot.id,
notes: snapshot['notes'],
userId: snapshot['userId']
);
}
}
Any help is appreciated!

I believe you are storing an empty note, which is the reason why the result from the database is empty.
This line:
if (notesController.text.isNotEmpty) // show error message
should become this:
if (notesController.text.isEmpty) // show error message
Also, this should probably change, too:
// This does nothing:
new TextEditingController().clear();
// To clear the controller:
notesController.text = '';
UPDATE
Change your code as follows to test if something
gets written into the database. Once this works, figure out how to use MyWidget correctly, as there are issues in there, too.
// OLD CODE
child: MyWidget(
textFields: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
),
// NEW CODE
child: TextField(
style: TextStyle (color: Color(0xFF192A4F),fontSize: 18,),
textCapitalization: TextCapitalization.sentences,
controller: notesController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.transparent),
),
),
),
I suggest to always only change small parts of code and ensure that your code works at each small step. Do not make too many changes at once.

Related

Unable to retrieve data from Firebase Realtime Database in Flutter Application [duplicate]

I am trying to create a simple app that adds posts to a firebase realtime database and shows them on a listview in flutter, but when I "post" it to the database, on the firebase console, the data value constantly appears as null. does anyone know what is wrong?
Here is a bit of my code -
post.dart
class Post {
Image coverImg;
File audioFile;
String body;
String author;
Set usersLiked = {};
DatabaseReference _id;
Post(this.body, this.author);
void likePost(User user) {
if (this.usersLiked.contains(user.uid)) {
this.usersLiked.remove(user.uid);
} else {
this.usersLiked.add(user.uid);
}
}
void update() {
updatePost(this, this._id);
}
void setId(DatabaseReference id) {
this._id = id;
}
Map<String, dynamic> toJson() {
return {
'body': this.body,
'author': this.author,
'usersLiked': this.usersLiked.toList()
};
}
}
Post createPost(record) {
Map<String, dynamic> attributes = {
'author': '',
'usersLiked': [],
'body': ''
};
record.forEach((key, value) => {attributes[key] = value});
Post post = new Post(attributes['body'], attributes['author']);
post.usersLiked = new Set.from(attributes['usersLiked']);
return post;
}
class PostList extends StatefulWidget {
final List<Post> listItems;
final User user;
PostList(this.listItems, this.user);
#override
_PostListState createState() => _PostListState();
}
class _PostListState extends State<PostList> {
void like(Function callBack) {
this.setState(() {
callBack();
});
}
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: this.widget.listItems.length,
itemBuilder: (context, index) {
var post = this.widget.listItems[index];
return Card(
elevation: 7.0,
color: Colors.white,
child: Column(
children: [
Row(
children: [
IconButton(
icon: Icon(
Icons.play_circle_outline,
color: Colors.black,
size: 30,
),
onPressed: () {},
),
Expanded(
child: ListTile(
title: Text(post.body,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.black)),
subtitle: Text(post.author,
style: TextStyle(color: Colors.black)),
),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(post.usersLiked.length.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600)),
IconButton(
icon: Icon(
Icons.thumb_up,
color: post.usersLiked.contains(widget.user.uid)
? Colors.blue
: Colors.black,
),
onPressed: () =>
this.like(() => post.likePost(widget.user)),
)
],
))
],
)
],
));
},
);
}
}
database.dart
final databaseReference = FirebaseDatabase.instance.reference();
DatabaseReference savePost(Post post) {
var id = databaseReference.child('posts/').push();
id.set(post.toJson());
return id;
}
void updatePost(Post post, DatabaseReference id) {
id.update(post.toJson());
}
Future<List<Post>> getAllPosts() async {
DataSnapshot dataSnapshot = await databaseReference.child('posts/').once();
List<Post> posts = [];
if (dataSnapshot.value != null) {
dataSnapshot.value.forEach((key, value) {
Post post = createPost(value);
post.setId(databaseReference.child('posts/' + key));
posts.add(post);
});
}
return posts;
}
home.dart
class UserInfoScreen extends StatefulWidget {
const UserInfoScreen({Key key, User user})
: _user = user,
super(key: key);
final User _user;
#override
_UserInfoScreenState createState() => _UserInfoScreenState();
}
class _UserInfoScreenState extends State<UserInfoScreen> {
User _user;
bool _isSigningOut = false;
List<Post> posts = [];
void newPost(String text) {
var post = new Post(text, widget._user.displayName);
post.setId(savePost(post));
this.setState(() {
posts.add(post);
});
}
void updatePosts() {
getAllPosts().then((posts) => {
this.setState(() {
this.posts = posts;
})
});
}
Route _routeToSignInScreen() {
return PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) => SignInScreen(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
var begin = Offset(-1.0, 0.0);
var end = Offset.zero;
var curve = Curves.ease;
var tween =
Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
return SlideTransition(
position: animation.drive(tween),
child: child,
);
},
);
}
#override
void initState() {
_user = widget._user;
// HOME PAGE
pageList.add(Scaffold(
backgroundColor: Colors.white,
body: Column(children: [
Expanded(
child: PostList(this.posts, _user),
),
]),
));
pageList.add(Test1());
pageList.add(Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
TextInputWidget(this.newPost, "Title:"),
],
),
));
pageList.add(Test3());
// ACCOUNT PAGE
pageList.add(
Scaffold(
backgroundColor: Colors.white,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(),
_user.photoURL != null
? ClipOval(
child: Material(
color: Colors.grey.withOpacity(0.3),
child: Image.network(
_user.photoURL,
fit: BoxFit.fitHeight,
),
),
)
: ClipOval(
child: Material(
color: Colors.grey.withOpacity(0.3),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(
Icons.person,
size: 60,
color: Colors.black,
),
),
),
),
SizedBox(height: 16.0),
Text(
'${_user.displayName}',
style: TextStyle(
color: Colors.black,
fontSize: 26,
fontWeight: FontWeight.w700),
),
SizedBox(height: 8.0),
Text(
' ${_user.email} ',
style: TextStyle(
color: Colors.black,
fontSize: 20,
letterSpacing: 0.5,
),
),
SizedBox(height: 60.0),
_isSigningOut
? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
)
: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Colors.redAccent,
),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
onPressed: () async {
setState(() {
_isSigningOut = true;
});
await Authentication.signOut(context: context);
setState(() {
_isSigningOut = false;
});
Navigator.of(context)
.pushReplacement(_routeToSignInScreen());
},
child: Padding(
padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
child: Text(
'Logout',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
],
),
),
);
super.initState();
updatePosts();
}
#override
List<Widget> pageList = List<Widget>();
int _currentIndex = 0;
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.white,
title: Text(
'SoundFX',
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: IndexedStack(
index: _currentIndex,
children: pageList,
),
bottomNavigationBar: BottomNavigationBar(
unselectedItemColor: Colors.grey,
selectedItemColor: Colors.blue,
backgroundColor: Colors.white,
elevation: 19.0,
onTap: onTabTapped,
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(
Icons.add_circle,
size: 40,
),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.videocam),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Container(
height: 1.0,
)),
],
),
);
}
}
class Test1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
);
}
}
class Test2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
);
}
}
class Test3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.yellow,
);
}
}
text-input.dart
class TextInputWidget extends StatefulWidget {
final Function(String) callback;
String label;
TextInputWidget(this.callback, this.label);
#override
_TextInputWidgetState createState() => _TextInputWidgetState();
}
class _TextInputWidgetState extends State<TextInputWidget> {
final controller = TextEditingController();
#override
void dispose() {
super.dispose();
controller.dispose();
}
void click() {
widget.callback(controller.text);
FocusScope.of(context).unfocus();
controller.clear();
}
void pickFiles() async {
FilePickerResult result =
await FilePicker.platform.pickFiles(type: FileType.any);
File file = File(result.files.first.path);
print(file);
}
#override
Widget build(BuildContext context) {
return Container(
height: 400,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Container(
padding: EdgeInsets.all(20.0),
child: TextField(
controller: this.controller,
decoration: InputDecoration(
labelText: this.widget.label,
))),
),
Container(
child: ElevatedButton(onPressed: this.click, child: Text('Post')),
),
Container(
child:
ElevatedButton(onPressed: this.pickFiles, child: Text('test')),
)
],
),
);
}
}
PS: Also, note that some of the functions and classes are unused or basically useless, and some of the names are very stupid, but please do not comment on those if they are not related to the question, as those are just for some tests for features for me to add into the application.
Also, note that i followed this tutorial - https://www.youtube.com/playlist?list=PLzMcBGfZo4-knQWGK2IC49Q_5AnQrFpzv
firebaser here
Most likely the Firebase SDK is unable to read the URL of the database from its config file, because your database is hosted outside of the default (US) region.
If that is indeed the cause, you should specify the database URL in your code. By specifying it in your code, the SDK should able to connect to the database instance no matter what region it is hosted in.
This mean you should get your database with
FirebaseDatabase("your database URL").reference()
// Or
FirebaseDatabase(databaseURL: "your database URL").reference()
instead of
FirebaseDatabase.instance.reference()
This is documented here:
To get a reference to a database other than a us-central1 default dstabase, you must pass the database URL to getInstance() (or Kotlin+KTX database()) . For a us-central1 default database, you can call getInstance() (or database) without arguments.
So while this is documented, it is incredibly easy to overlook. I'm checking with our team if there's something we can do to make this configuration problem more obvious.

Why is the Firebase Realtime Database's data appearing as null in the console?

I am trying to create a simple app that adds posts to a firebase realtime database and shows them on a listview in flutter, but when I "post" it to the database, on the firebase console, the data value constantly appears as null. does anyone know what is wrong?
Here is a bit of my code -
post.dart
class Post {
Image coverImg;
File audioFile;
String body;
String author;
Set usersLiked = {};
DatabaseReference _id;
Post(this.body, this.author);
void likePost(User user) {
if (this.usersLiked.contains(user.uid)) {
this.usersLiked.remove(user.uid);
} else {
this.usersLiked.add(user.uid);
}
}
void update() {
updatePost(this, this._id);
}
void setId(DatabaseReference id) {
this._id = id;
}
Map<String, dynamic> toJson() {
return {
'body': this.body,
'author': this.author,
'usersLiked': this.usersLiked.toList()
};
}
}
Post createPost(record) {
Map<String, dynamic> attributes = {
'author': '',
'usersLiked': [],
'body': ''
};
record.forEach((key, value) => {attributes[key] = value});
Post post = new Post(attributes['body'], attributes['author']);
post.usersLiked = new Set.from(attributes['usersLiked']);
return post;
}
class PostList extends StatefulWidget {
final List<Post> listItems;
final User user;
PostList(this.listItems, this.user);
#override
_PostListState createState() => _PostListState();
}
class _PostListState extends State<PostList> {
void like(Function callBack) {
this.setState(() {
callBack();
});
}
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: this.widget.listItems.length,
itemBuilder: (context, index) {
var post = this.widget.listItems[index];
return Card(
elevation: 7.0,
color: Colors.white,
child: Column(
children: [
Row(
children: [
IconButton(
icon: Icon(
Icons.play_circle_outline,
color: Colors.black,
size: 30,
),
onPressed: () {},
),
Expanded(
child: ListTile(
title: Text(post.body,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.black)),
subtitle: Text(post.author,
style: TextStyle(color: Colors.black)),
),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(post.usersLiked.length.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600)),
IconButton(
icon: Icon(
Icons.thumb_up,
color: post.usersLiked.contains(widget.user.uid)
? Colors.blue
: Colors.black,
),
onPressed: () =>
this.like(() => post.likePost(widget.user)),
)
],
))
],
)
],
));
},
);
}
}
database.dart
final databaseReference = FirebaseDatabase.instance.reference();
DatabaseReference savePost(Post post) {
var id = databaseReference.child('posts/').push();
id.set(post.toJson());
return id;
}
void updatePost(Post post, DatabaseReference id) {
id.update(post.toJson());
}
Future<List<Post>> getAllPosts() async {
DataSnapshot dataSnapshot = await databaseReference.child('posts/').once();
List<Post> posts = [];
if (dataSnapshot.value != null) {
dataSnapshot.value.forEach((key, value) {
Post post = createPost(value);
post.setId(databaseReference.child('posts/' + key));
posts.add(post);
});
}
return posts;
}
home.dart
class UserInfoScreen extends StatefulWidget {
const UserInfoScreen({Key key, User user})
: _user = user,
super(key: key);
final User _user;
#override
_UserInfoScreenState createState() => _UserInfoScreenState();
}
class _UserInfoScreenState extends State<UserInfoScreen> {
User _user;
bool _isSigningOut = false;
List<Post> posts = [];
void newPost(String text) {
var post = new Post(text, widget._user.displayName);
post.setId(savePost(post));
this.setState(() {
posts.add(post);
});
}
void updatePosts() {
getAllPosts().then((posts) => {
this.setState(() {
this.posts = posts;
})
});
}
Route _routeToSignInScreen() {
return PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) => SignInScreen(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
var begin = Offset(-1.0, 0.0);
var end = Offset.zero;
var curve = Curves.ease;
var tween =
Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
return SlideTransition(
position: animation.drive(tween),
child: child,
);
},
);
}
#override
void initState() {
_user = widget._user;
// HOME PAGE
pageList.add(Scaffold(
backgroundColor: Colors.white,
body: Column(children: [
Expanded(
child: PostList(this.posts, _user),
),
]),
));
pageList.add(Test1());
pageList.add(Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
TextInputWidget(this.newPost, "Title:"),
],
),
));
pageList.add(Test3());
// ACCOUNT PAGE
pageList.add(
Scaffold(
backgroundColor: Colors.white,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(),
_user.photoURL != null
? ClipOval(
child: Material(
color: Colors.grey.withOpacity(0.3),
child: Image.network(
_user.photoURL,
fit: BoxFit.fitHeight,
),
),
)
: ClipOval(
child: Material(
color: Colors.grey.withOpacity(0.3),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(
Icons.person,
size: 60,
color: Colors.black,
),
),
),
),
SizedBox(height: 16.0),
Text(
'${_user.displayName}',
style: TextStyle(
color: Colors.black,
fontSize: 26,
fontWeight: FontWeight.w700),
),
SizedBox(height: 8.0),
Text(
' ${_user.email} ',
style: TextStyle(
color: Colors.black,
fontSize: 20,
letterSpacing: 0.5,
),
),
SizedBox(height: 60.0),
_isSigningOut
? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
)
: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Colors.redAccent,
),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
onPressed: () async {
setState(() {
_isSigningOut = true;
});
await Authentication.signOut(context: context);
setState(() {
_isSigningOut = false;
});
Navigator.of(context)
.pushReplacement(_routeToSignInScreen());
},
child: Padding(
padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
child: Text(
'Logout',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
],
),
),
);
super.initState();
updatePosts();
}
#override
List<Widget> pageList = List<Widget>();
int _currentIndex = 0;
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.white,
title: Text(
'SoundFX',
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: IndexedStack(
index: _currentIndex,
children: pageList,
),
bottomNavigationBar: BottomNavigationBar(
unselectedItemColor: Colors.grey,
selectedItemColor: Colors.blue,
backgroundColor: Colors.white,
elevation: 19.0,
onTap: onTabTapped,
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(
Icons.add_circle,
size: 40,
),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.videocam),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Container(
height: 1.0,
)),
],
),
);
}
}
class Test1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
);
}
}
class Test2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
);
}
}
class Test3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.yellow,
);
}
}
text-input.dart
class TextInputWidget extends StatefulWidget {
final Function(String) callback;
String label;
TextInputWidget(this.callback, this.label);
#override
_TextInputWidgetState createState() => _TextInputWidgetState();
}
class _TextInputWidgetState extends State<TextInputWidget> {
final controller = TextEditingController();
#override
void dispose() {
super.dispose();
controller.dispose();
}
void click() {
widget.callback(controller.text);
FocusScope.of(context).unfocus();
controller.clear();
}
void pickFiles() async {
FilePickerResult result =
await FilePicker.platform.pickFiles(type: FileType.any);
File file = File(result.files.first.path);
print(file);
}
#override
Widget build(BuildContext context) {
return Container(
height: 400,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Container(
padding: EdgeInsets.all(20.0),
child: TextField(
controller: this.controller,
decoration: InputDecoration(
labelText: this.widget.label,
))),
),
Container(
child: ElevatedButton(onPressed: this.click, child: Text('Post')),
),
Container(
child:
ElevatedButton(onPressed: this.pickFiles, child: Text('test')),
)
],
),
);
}
}
PS: Also, note that some of the functions and classes are unused or basically useless, and some of the names are very stupid, but please do not comment on those if they are not related to the question, as those are just for some tests for features for me to add into the application.
Also, note that i followed this tutorial - https://www.youtube.com/playlist?list=PLzMcBGfZo4-knQWGK2IC49Q_5AnQrFpzv
firebaser here
Most likely the Firebase SDK is unable to read the URL of the database from its config file, because your database is hosted outside of the default (US) region.
If that is indeed the cause, you should specify the database URL in your code. By specifying it in your code, the SDK should able to connect to the database instance no matter what region it is hosted in.
This mean you should get your database with
FirebaseDatabase("your database URL").reference()
// Or
FirebaseDatabase(databaseURL: "your database URL").reference()
instead of
FirebaseDatabase.instance.reference()
This is documented here:
To get a reference to a database other than a us-central1 default dstabase, you must pass the database URL to getInstance() (or Kotlin+KTX database()) . For a us-central1 default database, you can call getInstance() (or database) without arguments.
So while this is documented, it is incredibly easy to overlook. I'm checking with our team if there's something we can do to make this configuration problem more obvious.

sucessfully authenticated but can't write in firebase database using flutter [duplicate]

I am trying to create a simple app that adds posts to a firebase realtime database and shows them on a listview in flutter, but when I "post" it to the database, on the firebase console, the data value constantly appears as null. does anyone know what is wrong?
Here is a bit of my code -
post.dart
class Post {
Image coverImg;
File audioFile;
String body;
String author;
Set usersLiked = {};
DatabaseReference _id;
Post(this.body, this.author);
void likePost(User user) {
if (this.usersLiked.contains(user.uid)) {
this.usersLiked.remove(user.uid);
} else {
this.usersLiked.add(user.uid);
}
}
void update() {
updatePost(this, this._id);
}
void setId(DatabaseReference id) {
this._id = id;
}
Map<String, dynamic> toJson() {
return {
'body': this.body,
'author': this.author,
'usersLiked': this.usersLiked.toList()
};
}
}
Post createPost(record) {
Map<String, dynamic> attributes = {
'author': '',
'usersLiked': [],
'body': ''
};
record.forEach((key, value) => {attributes[key] = value});
Post post = new Post(attributes['body'], attributes['author']);
post.usersLiked = new Set.from(attributes['usersLiked']);
return post;
}
class PostList extends StatefulWidget {
final List<Post> listItems;
final User user;
PostList(this.listItems, this.user);
#override
_PostListState createState() => _PostListState();
}
class _PostListState extends State<PostList> {
void like(Function callBack) {
this.setState(() {
callBack();
});
}
#override
void initState() {
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: this.widget.listItems.length,
itemBuilder: (context, index) {
var post = this.widget.listItems[index];
return Card(
elevation: 7.0,
color: Colors.white,
child: Column(
children: [
Row(
children: [
IconButton(
icon: Icon(
Icons.play_circle_outline,
color: Colors.black,
size: 30,
),
onPressed: () {},
),
Expanded(
child: ListTile(
title: Text(post.body,
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.black)),
subtitle: Text(post.author,
style: TextStyle(color: Colors.black)),
),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(post.usersLiked.length.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600)),
IconButton(
icon: Icon(
Icons.thumb_up,
color: post.usersLiked.contains(widget.user.uid)
? Colors.blue
: Colors.black,
),
onPressed: () =>
this.like(() => post.likePost(widget.user)),
)
],
))
],
)
],
));
},
);
}
}
database.dart
final databaseReference = FirebaseDatabase.instance.reference();
DatabaseReference savePost(Post post) {
var id = databaseReference.child('posts/').push();
id.set(post.toJson());
return id;
}
void updatePost(Post post, DatabaseReference id) {
id.update(post.toJson());
}
Future<List<Post>> getAllPosts() async {
DataSnapshot dataSnapshot = await databaseReference.child('posts/').once();
List<Post> posts = [];
if (dataSnapshot.value != null) {
dataSnapshot.value.forEach((key, value) {
Post post = createPost(value);
post.setId(databaseReference.child('posts/' + key));
posts.add(post);
});
}
return posts;
}
home.dart
class UserInfoScreen extends StatefulWidget {
const UserInfoScreen({Key key, User user})
: _user = user,
super(key: key);
final User _user;
#override
_UserInfoScreenState createState() => _UserInfoScreenState();
}
class _UserInfoScreenState extends State<UserInfoScreen> {
User _user;
bool _isSigningOut = false;
List<Post> posts = [];
void newPost(String text) {
var post = new Post(text, widget._user.displayName);
post.setId(savePost(post));
this.setState(() {
posts.add(post);
});
}
void updatePosts() {
getAllPosts().then((posts) => {
this.setState(() {
this.posts = posts;
})
});
}
Route _routeToSignInScreen() {
return PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) => SignInScreen(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
var begin = Offset(-1.0, 0.0);
var end = Offset.zero;
var curve = Curves.ease;
var tween =
Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
return SlideTransition(
position: animation.drive(tween),
child: child,
);
},
);
}
#override
void initState() {
_user = widget._user;
// HOME PAGE
pageList.add(Scaffold(
backgroundColor: Colors.white,
body: Column(children: [
Expanded(
child: PostList(this.posts, _user),
),
]),
));
pageList.add(Test1());
pageList.add(Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
TextInputWidget(this.newPost, "Title:"),
],
),
));
pageList.add(Test3());
// ACCOUNT PAGE
pageList.add(
Scaffold(
backgroundColor: Colors.white,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(),
_user.photoURL != null
? ClipOval(
child: Material(
color: Colors.grey.withOpacity(0.3),
child: Image.network(
_user.photoURL,
fit: BoxFit.fitHeight,
),
),
)
: ClipOval(
child: Material(
color: Colors.grey.withOpacity(0.3),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(
Icons.person,
size: 60,
color: Colors.black,
),
),
),
),
SizedBox(height: 16.0),
Text(
'${_user.displayName}',
style: TextStyle(
color: Colors.black,
fontSize: 26,
fontWeight: FontWeight.w700),
),
SizedBox(height: 8.0),
Text(
' ${_user.email} ',
style: TextStyle(
color: Colors.black,
fontSize: 20,
letterSpacing: 0.5,
),
),
SizedBox(height: 60.0),
_isSigningOut
? CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
)
: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Colors.redAccent,
),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
onPressed: () async {
setState(() {
_isSigningOut = true;
});
await Authentication.signOut(context: context);
setState(() {
_isSigningOut = false;
});
Navigator.of(context)
.pushReplacement(_routeToSignInScreen());
},
child: Padding(
padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
child: Text(
'Logout',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
],
),
),
);
super.initState();
updatePosts();
}
#override
List<Widget> pageList = List<Widget>();
int _currentIndex = 0;
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.white,
title: Text(
'SoundFX',
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: IndexedStack(
index: _currentIndex,
children: pageList,
),
bottomNavigationBar: BottomNavigationBar(
unselectedItemColor: Colors.grey,
selectedItemColor: Colors.blue,
backgroundColor: Colors.white,
elevation: 19.0,
onTap: onTabTapped,
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(
Icons.add_circle,
size: 40,
),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.videocam),
title: Container(
height: 1.0,
)),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Container(
height: 1.0,
)),
],
),
);
}
}
class Test1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
);
}
}
class Test2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
);
}
}
class Test3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.yellow,
);
}
}
text-input.dart
class TextInputWidget extends StatefulWidget {
final Function(String) callback;
String label;
TextInputWidget(this.callback, this.label);
#override
_TextInputWidgetState createState() => _TextInputWidgetState();
}
class _TextInputWidgetState extends State<TextInputWidget> {
final controller = TextEditingController();
#override
void dispose() {
super.dispose();
controller.dispose();
}
void click() {
widget.callback(controller.text);
FocusScope.of(context).unfocus();
controller.clear();
}
void pickFiles() async {
FilePickerResult result =
await FilePicker.platform.pickFiles(type: FileType.any);
File file = File(result.files.first.path);
print(file);
}
#override
Widget build(BuildContext context) {
return Container(
height: 400,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Container(
padding: EdgeInsets.all(20.0),
child: TextField(
controller: this.controller,
decoration: InputDecoration(
labelText: this.widget.label,
))),
),
Container(
child: ElevatedButton(onPressed: this.click, child: Text('Post')),
),
Container(
child:
ElevatedButton(onPressed: this.pickFiles, child: Text('test')),
)
],
),
);
}
}
PS: Also, note that some of the functions and classes are unused or basically useless, and some of the names are very stupid, but please do not comment on those if they are not related to the question, as those are just for some tests for features for me to add into the application.
Also, note that i followed this tutorial - https://www.youtube.com/playlist?list=PLzMcBGfZo4-knQWGK2IC49Q_5AnQrFpzv
firebaser here
Most likely the Firebase SDK is unable to read the URL of the database from its config file, because your database is hosted outside of the default (US) region.
If that is indeed the cause, you should specify the database URL in your code. By specifying it in your code, the SDK should able to connect to the database instance no matter what region it is hosted in.
This mean you should get your database with
FirebaseDatabase("your database URL").reference()
// Or
FirebaseDatabase(databaseURL: "your database URL").reference()
instead of
FirebaseDatabase.instance.reference()
This is documented here:
To get a reference to a database other than a us-central1 default dstabase, you must pass the database URL to getInstance() (or Kotlin+KTX database()) . For a us-central1 default database, you can call getInstance() (or database) without arguments.
So while this is documented, it is incredibly easy to overlook. I'm checking with our team if there's something we can do to make this configuration problem more obvious.

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.

Firestore flutter app gets error after 2 seconds?

I'm using the flutter_calendar_carousel package for my planner app. I'm getting the data from firestore so it shows up for like 2 seconds and then I get this error "package:flutter/src/widgets/container.dart': Failed assertion: line 316 pos 15: 'padding == null || padding.isNonNegative': is not true."
This is my code.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart' show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:intl/intl.dart' show DateFormat;
bool onDarkMode = false;
class MonthPageTest extends StatefulWidget {
#override
_MonthPageTestState createState() => _MonthPageTestState();
}
class _MonthPageTestState extends State<MonthPageTest> {
final databaseReference = Firestore.instance.collection("Planerino").document("UserSettings");
final databaseRef = Firestore.instance.collection("Eventhmonth");
darkmode() async{
try {
databaseReference.updateData({'Darkmode': onDarkMode});
}catch (e) {
print(e.toString());
}
}
#override
void initState(){
super.initState();
}
#override
void dispose(){
super.dispose();
}
toggleButton(){
setState(() {
onDarkMode = !onDarkMode;
});
darkmode();
}
//calender
DateTime _currentDate = DateTime.now();
static Widget _eventIcon = new Container(
width: 40.0,
height: 40.0,
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(1000)),
border: Border.all(color: Colors.blue, width: 6.0)),
child: new Icon(
Icons.person,
color: Colors.amber,
size: 40.0,
),
);
//function
EventList<Event> _markedDateMap = new EventList<Event>(
events: {
new DateTime(2020, 6, 24): [
new Event(
date: new DateTime(2020, 6, 13),
icon: _eventIcon,
dot: Container(
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
color: Colors.red,
),
),
],
},
);
Widget builderino(BuildContext context){
return StreamBuilder(
stream: databaseRef.snapshots(),
builder: (context, dataSnapshot){
var ref = dataSnapshot.data.documents;
for (var i = 0; i < ref.length; i++) {
String valueString = ref[i]['color'].split('(0x')[1].split(')')[0];
int value = int.parse(valueString, radix: 16);
Color newColor = new Color(value);
_markedDateMap.add(new DateTime(ref[i]['year'], ref[i]['month'], ref[i]['day']),
Event(
date: new DateTime(2020, 6, 13),
icon: _eventIcon,
dot: Container(
child: Padding(
padding: EdgeInsets.only(top: 90.0),
child: Container( alignment: Alignment.center, child: Text(ref[i]['description'], style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.w300), textAlign: TextAlign.center,)),
),
margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
decoration: BoxDecoration(color: newColor),
),
));
}
return CalendarCarousel<Event>(
onDayPressed: (DateTime date, List<Event> events) {
this.setState(() => _currentDate = date);
events.forEach((event) => print(event.title));
},
weekendTextStyle: TextStyle(
color: Colors.red,
fontSize: 28.0,
),
markedDatesMap: _markedDateMap,
markedDateIconBuilder: (event) {
return event.dot;
},
showIconBehindDayText: true,
markedDateShowIcon: true,
markedDateIconMaxShown: 1000,
todayButtonColor: Colors.black12,
markedDateMoreShowTotal: true,
headerTextStyle: TextStyle(fontSize: 34.0, color: Colors.blue[300]),
daysTextStyle: TextStyle(fontSize: 28.0, color: onDarkMode ? Colors.white : Colors.black45),
todayTextStyle: TextStyle(fontSize: 28.0, color: onDarkMode ? Colors.white : Colors.black45),
weekdayTextStyle: TextStyle(fontSize: 28.0),
);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: onDarkMode ? Colors.black87 : Colors.white,
margin: EdgeInsets.symmetric(horizontal: 16.0),
child: builderino(context),
),
);
}
}
Do i need to make it async or what is the problem?
from this SO answer
TLDR
Flutter has a sophisticated but effective algorithm for rendering its widgets. Margins and Paddings are analyzed at runtime, and the final size and position of the widget is determined. When you try to issue a negative margin you are purposefully creating a not valid layout where a widget is somehow dropping out of the space it is supposed to occupy.
Consider reading the doc here.

Resources