Flutter firebase chat problem in redirecting user chatroom - flutter

Hi guys i'm a begginer in flutter development , i am stuck in a problem,
problem is i want to redirect from selected (homepage.dart file) user in the list to chatroom where i can chat this user but i am not able to do, here is problem i'm facing: Anyone give me solution .
code:-
homepage.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jobong/model/chatroom_model.dart';
import 'package:jobong/model/signup.dart';
import 'package:jobong/view/chatroom.dart';
class HomePage extends StatefulWidget {
final List<User>? users;
const HomePage({Key? key, this.users}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final auth = FirebaseAuth.instance;
final systemColor =
const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
final User? currentUser = FirebaseAuth.instance.currentUser;
final String uid = FirebaseAuth.instance.currentUser!.uid;
final searchController = TextEditingController();
String search = '';
#override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(systemColor);
return Scaffold(
backgroundColor: Colors.grey[300],
drawer: const Drawer(
child: DrawerPage(),
),
appBar: AppBar(
titleSpacing: 0,
backgroundColor: Colors.blue[900],
title: Text(
"ChatApp",
style: GoogleFonts.raleway(),
),
actions: [
IconButton(
onPressed: () async {
await FirebaseAuth.instance.signOut();
setState(() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SignUp()),
);
});
},
icon: const Icon(Icons.logout_outlined),
),
],
),
body: Column(
children: [
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
controller: searchController,
onChanged: (String value) {
search = value;
},
decoration: InputDecoration(
hintText: 'Search user',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
hintStyle: GoogleFonts.raleway(
fontSize: 16, fontWeight: FontWeight.normal),
),
),
),
ElevatedButton(
onPressed: () {
setState(() {});
},
child: Text(
"Search",
style: GoogleFonts.raleway(),
),
),
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream:
FirebaseFirestore.instance.collection('Users')
.where('uid',isNotEqualTo: currentUser!.uid).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot snap = snapshot.data!.docs[index];
final chatRoomModel = ChatRoomModel(
friendName: currentUser!.displayName.toString(),
friendUid: currentUser!.uid,
friendEmail: currentUser!.email.toString(),
);
final targetUserName = chatRoomModel.friendName;
final targetUserEmail = chatRoomModel.friendEmail ;
final targetUserUid = chatRoomModel.friendUid;
if (search.isEmpty) {
return ListTile(
title: Text(snap['name']),
subtitle: Text(snap['email']),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ChatRoom(
friendName: snap['name'] ,
friendEmail: snap['email'],
friendUid: snap['uid'],
),
),
);
},
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
}
if (snap['name'].toString().toLowerCase().startsWith(search.toLowerCase()) ||
snap['name'].toString().toUpperCase().startsWith(search.toUpperCase())) {
return ListTile(
title: Text(snap['name']),
subtitle: Text(snap['email']),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ChatRoom(
friendName: snap['name'] ,
friendEmail: snap['email'],
friendUid: snap['uid'],
),
),
);
},
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
}
return Container();
},
);
} else if (snapshot.hasError) {
return const Center(
child: Text("Something went wrong!"),
);
} else {
return Container();
}
},
),
),
],
),
);
}
}
//..............................User Details Fetch here ??..........................................
class DrawerPage extends StatefulWidget {
const DrawerPage({Key? key}) : super(key: key);
#override
State<DrawerPage> createState() => _DrawerPageState();
}
class _DrawerPageState extends State<DrawerPage> {
#override
void initState() {
super.initState();
getUserData();
}
String name = '';
String email = '';
String password = '';
final currentUser = FirebaseAuth.instance.currentUser;
Future<void> getUserData() async {
final user = await FirebaseFirestore.instance
.collection('Users')
.doc(currentUser!.uid)
.get();
setState(() {
name = user.data()!['name'];
email = user.data()!['email'];
password = user.data()!['password'];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Name: $name',
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal, fontSize: 16),
),
const SizedBox(height: 10),
Text(
'Email: $email',
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal, fontSize: 16),
),
const SizedBox(height: 10),
Text(
'Password: $password',
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal, fontSize: 16),
),
],
),
),
);
}
}
second chatroom.dart file =================================
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jobong/model/chatroom_model.dart';
class ChatRoom extends StatefulWidget {
final ChatRoomModel friendName;
final ChatRoomModel friendUid;
final ChatRoomModel friendEmail;
const ChatRoom({
Key? key,
required this.friendName, required this.friendUid ,
required this.friendEmail
}) : super(key: key);
#override
State<ChatRoom> createState() => _ChatRoomState();
}
class _ChatRoomState extends State<ChatRoom> {
void showToast(String message) {
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
final email = FirebaseAuth.instance.currentUser!.email;
void sendMessage() async {
try{
await FirebaseFirestore.instance.collection('chats')
.doc(uid).collection('messages').doc()
.set({
'sender':email,
'receiver':widget.friendUid,
'message':_message.text.trim(),
'time':FieldValue.serverTimestamp(),
});
}on FirebaseAuthException catch (e) {
showToast('${e.message}');
}
}
final bool isMe = false;
final _message = TextEditingController();
final uid = FirebaseAuth.instance.currentUser!.uid;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Column(
children: [
Text(
widget.friendName.toString(),
style: GoogleFonts.lato(),
),
Text(
widget.friendEmail.toString(),
style: GoogleFonts.lato(),
),
],
),
),
body: Column(
children: [
Expanded(
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('chats')
.doc(uid)
.collection('messages')
.doc()
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(color: Colors.blue),
);
} else {
return ListView.builder(
shrinkWrap: true,
reverse: true,
itemCount: snapshot.data!.doc.length,
itemBuilder: (BuildContext context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: isMe
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
borderRadius: isMe
? BorderRadius.circular(15.0)
: BorderRadius.circular(15.0),
color: isMe
? Colors.green[500]
: Colors.red[500]),
child: Center(
child: Text(_message.toString(),
style: isMe
? GoogleFonts.lato(color: Colors.black)
: GoogleFonts.lato(
color: Colors.white)),
),
),
],
),
);
},
);
}
},
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0, bottom: 8.0),
child: Container(
height: 60,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(25),
bottomRight: Radius.circular(25),
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
color: Colors.grey[900],
),
child: TextFormField(
controller: _message,
style: GoogleFonts.lato(color: Colors.white),
decoration: InputDecoration(
hintText: 'send a message ...',
hintStyle: GoogleFonts.lato(color: Colors.white),
border: InputBorder.none,
prefixIcon: const Icon(Icons.file_present_rounded,
color: Colors.white),
suffixIcon: GestureDetector(
onTap:sendMessage,
child: const Icon(Icons.near_me, color: Colors.white),
),
),
),
),
),
],
),
);
}
}

Related

The method 'data' was called on null. Receiver: null Tried calling: data() in flutter firebase chat app

The following NoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(dirty, state: _FutureBuilderState<DocumentSnapshot<Map<String, dynamic>>>#c2b0e):
The method 'data' was called on null.
Receiver: null
Tried calling: data()
in chatApp :-
here source code highlighted
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jobkar/public/model/user_model.dart';
import 'package:jobkar/public/view/navigation/message/chat_room.dart';
class Message extends StatefulWidget {
const Message({Key? key}) : super(key: key);
#override
State<Message> createState() => _MessageState();
}
class _MessageState extends State<Message> {
final currentUser = FirebaseAuth.instance.currentUser;
final searchController = TextEditingController();
String search = '';
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 50,
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color: Colors.white),
child: Row(
children: [
Flexible(
child: TextFormField(
controller: searchController,
onChanged: (value) {
search = value;
},
decoration: InputDecoration(
hintText: 'Search person',
border: InputBorder.none,
prefixIcon: const Icon(
Icons.dehaze,
size: 26,
color: Colors.black54,
),
hintStyle: GoogleFonts.raleway(
fontSize: 16, fontWeight: FontWeight.normal)),
),
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.black54),
child: Center(
child: IconButton(
onPressed: () {
setState(() {});
},
icon: const Icon(
Icons.search,
color: Colors.white,
),
),
),
),
),
],
),
),
),
Expanded(
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.doc(currentUser!.uid)
.collection('message')
.snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(
color: Colors.blue[900],
),
);
} else if (snapshot.hasError) {
return const Center(
child: Text("Something went wrong please try later"),
);
} else if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
var friendId = snapshot.data!.docs[index].id;
var lastMessage = snapshot.data!.docs[index]['lastMessage'];
return FutureBuilder(
future: FirebaseFirestore.instance.collection('users').doc(friendId).get(),
builder: (BuildContext context , AsyncSnapshot snapshot) {
**final userModel = UserModel.fromMap(snapshot.data.data() as Map<String,dynamic>);**
if (snapshot.hasData) {
var friend = snapshot.data;
if (search.isEmpty) {
return ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
ChatRoom(
userModel: userModel,
friendName: friend['name'],
friendImage: friend['imageUrl'],
friendId: friend['uid'],
friendEmail: friend['email']
),
),
);
},
title: Text(
friend['name'],
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
subtitle: Text(lastMessage,
overflow: TextOverflow.ellipsis,
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
} else if (friend['name']
.toString()
.toLowerCase()
.startsWith(search.toLowerCase()) ||
friend['name']
.toString()
.toUpperCase()
.startsWith(search.toUpperCase())) {
return ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
ChatRoom(
userModel: userModel,
friendName: friend['name'],
friendImage: friend['imageUrl'],
friendId: friend['uid'],
friendEmail: friend['email']
),
),
);
},
title: Text(
friend['name'],
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
subtitle: Text(lastMessage,
style: GoogleFonts.raleway(
fontWeight: FontWeight.normal),
),
leading: Container(
height: 45,
width: 45,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15.0),
color: Colors.white),
child: const Center(
child: Icon(Icons.person),
),
),
);
}
return Container();
}
return Container();
}
);
});
}
return Container();
},
),
),
],
),
);
}
}
Generate the model after getting data like
builder: (BuildContext context , AsyncSnapshot snapshot) {
if (snapshot.hasData) {
final mapData = snapshot.data.data() as Map?;
if(mapData == null) return Text("Got null data");
final userModel = UserModel.fromMap(mapData);
var friend = snapshot.data;

How to display phone number in the flutter app

I'm working on simple chat features in my app. I have used OTP login method to do this application. Firebase Authentication is working well in my application. I have already done the code for the simple chat app but I would like to display the user's phone number when they send chat. Example pic added below for better understanding about the need:
This is my code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../forum/message.dart';
class ForumScreen extends StatefulWidget {
String email;
ForumScreen({required this.email});
#override
_ForumScreenState createState() => _ForumScreenState(email: email);
}
class _ForumScreenState extends State<ForumScreen> {
String email;
_ForumScreenState({required this.email});
final fs = FirebaseFirestore.instance;
final _auth = FirebaseAuth.instance.currentUser;
final TextEditingController message = new TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Farmer's Forum"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
height: MediaQuery.of(context).size.height * 0.73,
child: messages(
email: email,
),
),
Row(
children: [
Expanded(
child: TextFormField(
controller: message,
decoration: InputDecoration(
filled: true,
fillColor: Colors.lightGreen,
hintText: 'message',
enabled: true,
contentPadding: const EdgeInsets.only(
left: 14.0, bottom: 8.0, top: 8.0),
focusedBorder: OutlineInputBorder(
borderSide: new BorderSide(color: Colors.black),
borderRadius: new BorderRadius.circular(10),
),
enabledBorder: UnderlineInputBorder(
borderSide: new BorderSide(color: Colors.black),
borderRadius: new BorderRadius.circular(10),
),
),
validator: (value) {},
onSaved: (value) {
message.text = value!;
},
),
),
IconButton(
onPressed: () {
if (message.text.isNotEmpty) {
fs.collection('Messages').doc().set({
'message': message.text.trim(),
'time': DateTime.now(),
'email': email,
});
message.clear();
}
},
icon: Icon(Icons.send_sharp),
),
],
),
],
),
),
);
}
}
message.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class messages extends StatefulWidget {
String email;
messages({required this.email});
#override
_messagesState createState() => _messagesState(email: email);
}
class _messagesState extends State<messages> {
String email;
_messagesState({required this.email});
Stream<QuerySnapshot> _messageStream = FirebaseFirestore.instance
.collection('Messages')
.orderBy('time')
.snapshots();
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _messageStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text("something is wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
physics: ScrollPhysics(),
shrinkWrap: true,
primary: true,
itemBuilder: (_, index) {
QueryDocumentSnapshot qs = snapshot.data!.docs[index];
Timestamp t = qs['time'];
DateTime d = t.toDate();
print(d.toString());
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Column(
crossAxisAlignment: email == qs['email']
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
SizedBox(
width: 300,
child: ListTile(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green,
),
borderRadius: BorderRadius.circular(10),
),
title: Text(
qs['email'],
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 200,
child: Text(
qs['message'],
softWrap: true,
style: TextStyle(
fontSize: 15,
),
),
),
Text(
d.hour.toString() + ":" + d.minute.toString(),
)
],
),
),
),
],
),
);
},
);
},
);
}
}
How should I read the phone number? I'm not sure how do we related both firebase authentication and cloud firestore.
If you have the information of the phone number you have to provide it to messages(email)
Also Widget names (like all class names) should begin with an uppercase
Something like:
class Messages extends StatefulWidget {
String email;
Messages({required this.email});
#override
_MessagesState createState() => _MessagesState(email: email);
}
class _MessagesState extends State<Messages> {
String email;
_MessagesState({required this.email});
Stream<QuerySnapshot> _messageStream = FirebaseFirestore.instance
.collection('Messages')
.orderBy('time')
.snapshots();
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: _messageStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text("something is wrong");
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
physics: ScrollPhysics(),
shrinkWrap: true,
primary: true,
itemBuilder: (_, index) {
QueryDocumentSnapshot qs = snapshot.data!.docs[index];
DateTime time = qs['time'].toDate();
String message = qs['message'];
String messageEmail = qs['email'];
String messagePhoneNumber = qs['phoneNumber'];
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Column(
crossAxisAlignment: email == messageEmail
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
SizedBox(
width: 300,
child: ListTile(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green,
),
borderRadius: BorderRadius.circular(10),
),
title: Text(
messageEmail == email ? email : messagePhoneNumber,
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: 200,
child: Text(
message,
softWrap: true,
style: TextStyle(
fontSize: 15,
),
),
),
Text(
time.hour.toString() + ":" + time.minute.toString(),
)
],
),
),
),
],
),
);
},
);
},
);
}
}
As I said, it depends on your provided data if there is a phoneNumber

Type 'Null' is not a subtype of type 'Timestamp' Flutter

In a chat screen , I want the local time to be published along with the chat message. It is publishing but I am getting an error every time when I post a chat.
The following _TypeError was thrown building StreamBuilder<QuerySnapshot<Object?>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Object?>, AsyncSnapshot<QuerySnapshot<Object?>>>#433c7):
type 'Null' is not a subtype of type 'Timestamp'
How to fix this error?
Here is the code for Chat Screen :
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import '../../animated_texts.dart'; import '../../constants.dart'; import '../../services/auth.dart';
import 'package:grouped_list/grouped_list.dart'; import 'package:intl/intl.dart';
final FirebaseFirestore _firestore = FirebaseFirestore.instance; late User loggedInUser;
class ChatScreen extends StatefulWidget { const ChatScreen({Key? key}) : super(key: key);
#override _ChatScreenState createState() => _ChatScreenState(); }
class _ChatScreenState extends State<ChatScreen> { final messageTextController = TextEditingController(); late String messageTexts; final FirebaseAuth _authService = FirebaseAuth.instance; final AuthService _authLogOut = AuthService();
#override void initState() {
super.initState();
getCurrentUser(); }
void getCurrentUser() {
try {
final user = _authService.currentUser;
if (user != null) {
loggedInUser = user;
//print(loggedInUser.uid.substring(loggedInUser.uid.length - 5));
}
} catch (e) {
//print('The Error : $e');
} }
#override Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
shadowColor: Colors.transparent,
leading: IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
onPressed: () {
Navigator.maybePop(context);
}),
actions: <Widget>[
IconButton(
icon: const Icon(
Icons.exit_to_app,
color: Colors.white,
),
onPressed: () {
openDialog();
}),
],
centerTitle: true,
title: const AnimatedTitle(
text: 'AnonC',
fontSize: 25.0,
),
),
body: SafeArea(
child: Container(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const MessagesStream(),
Container(
color: Colors.green,
//blueGrey[900],
padding: const EdgeInsets.all(10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: messageTextController,
maxLines: null,
keyboardType: TextInputType.multiline,
textInputAction: TextInputAction.newline,
textCapitalization: TextCapitalization.sentences,
autocorrect: true,
enableSuggestions: true,
onChanged: (value) {
messageTexts = value;
},
decoration: kMessageTextFieldDecoration,
),
),
Container(
padding: const EdgeInsets.all(3),
decoration: const BoxDecoration(
color: Colors.white54,
shape: BoxShape.circle,
),
child: TextButton(
onPressed: () {
messageTextController.clear();
_firestore.collection('chatMessages').add({
'messages': messageTexts,
'name': 'Anon - ' +
loggedInUser.uid
.substring(loggedInUser.uid.length - 5),
'userEmoji': 'user emoji',
'timestamp': FieldValue.serverTimestamp(),
});
// messageTexts + loggedInUser;
},
child: Icon(
Icons.send_outlined,
size: 35,
color: Colors.blueGrey.shade900,
),
),
),
],
),
),
],
),
),
),
); }
Future openDialog() => showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.lightGreenAccent,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(18.0))),
title: const Text(
"Are You sure you want to Log out?",
style: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
content: const Text(
"Would Love to Welcome You back again!",
style: TextStyle(
color: Colors.black,
fontStyle: FontStyle.italic,
fontSize: 18,
),
),
actions: [
TextButton(
child: const Text("Yes"),
onPressed: () {
_authLogOut.signOut();
Navigator.pop(context, '/');
},
),
TextButton(
child: const Text("No"),
onPressed: () {
Navigator.pop(context);
},
),
],
),
); }
class MessagesStream extends StatelessWidget { const MessagesStream({Key? key}) : super(key: key);
#override Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _firestore
.collection('chatMessages')
.orderBy('timestamp', descending: true)
.snapshots(),
builder: (context, snapshot) {
List<MessageBubble> messages = [];
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(
backgroundColor: Colors.orange,
),
);
}
final chatMessages = snapshot.data!.docs;
for (var message in chatMessages) {
final messageText = message['messages'];
final messageSender = message['name'];
final currentUser =
loggedInUser.uid.substring(loggedInUser.uid.length - 5);
final timeStamps = message['timestamp'];
if (currentUser == messageSender) {
currentUser;
// //The message is from the logged in user
}
final messageHolder = MessageBubble(
sender: messageSender,
date: DateTime.now().subtract(const Duration(minutes: 1)),
text: messageText,
isME: currentUser == messageSender,
time: timeStamps,
);
messages.add(messageHolder);
}
return Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 1),
child: Container(
padding: const EdgeInsets.all(5),
decoration: const BoxDecoration(
color: Colors.green,
//blueGrey[900],
borderRadius: BorderRadius.only(
topRight: Radius.circular(55),
topLeft: Radius.circular(55),
),
),
// child: ListView(
// physics: const BouncingScrollPhysics(),
// reverse: true,
// // ignore: prefer_const_constructors
// padding: EdgeInsets.all(15),
// children: messageHolders,
// ),
child: GroupedListView<MessageBubble, DateTime>(
padding: const EdgeInsets.all(15),
reverse: true,
//order: GroupedListOrder.DESC,
//padding: const EdgeInsets.only(top: 1),
elements: messages,
groupBy: (messages) => DateTime(
messages.date.year,
messages.date.month,
messages.date.day,
),
groupHeaderBuilder: (messages) => SizedBox(
height: 50,
child: Center(
child: Card(
color: Colors.lightBlueAccent,
child: Padding(
padding: const EdgeInsets.all(4),
child: Text(
DateFormat.yMMMd().format(messages.date),
style: const TextStyle(color: Colors.white),
),
),
),
),
),
physics: const BouncingScrollPhysics(),
useStickyGroupSeparators: true,
floatingHeader: true,
itemBuilder: (context, MessageBubble messages) => messages,
),
),
),
);
}); } }
class MessageBubble extends StatelessWidget { final String text; final DateTime date; final bool isME; final String sender; final Timestamp time;
// ignore: use_key_in_widget_constructors const MessageBubble({
required this.text,
required this.date,
required this.isME,
required this.sender,
required this.time, });
#override Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(11.0),
child: Column(
crossAxisAlignment:
isME ? CrossAxisAlignment.start : CrossAxisAlignment.end,
children: [
Text(sender),
const SizedBox(height: 10),
Material(
color: isME ? Colors.lightGreenAccent[100] : Colors.brown[100],
elevation: 10,
borderRadius: isME
? const BorderRadius.only(
topLeft: Radius.circular(-50),
bottomRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
topRight: Radius.circular(10),
)
: const BorderRadius.only(
topRight: Radius.circular(-50),
bottomRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
topLeft: Radius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
text,
style: TextStyle(
color: isME ? Colors.blueGrey : Colors.black,
fontWeight: FontWeight.normal),
),
),
),
const SizedBox(height: 10),
Text(
DateFormat.jm().format(DateTime.now()),
//DateTime.now().toLocal().toString(),
//DateFormat.jm().format(DateTime.now().toLocal()),
//DateTime.now().subtract(const Duration(minutes: 1)).toString(),
//hour.toString()),
//DateFormat.jm().format(DateTime.now()),
//.format(messages.timeStamp)
),
],
),
); } }
the problem is that timeStamps will get a null value for some milliseconds, in that time you can put currentTime instead
final currentTime = Timestamp.fromMicrosecondsSinceEpoch(DateTime.now().millisecondsSinceEpoch);
final timeStamps = message['timestamp'] == null ? currentTime : message['timestamp'] as Timestamp;

Does anyone know what's going on with my Listview?

I needed to insert a TextField to search/filter records, but I don't know what's going on.
When I click on the "Cães" option of the BottomNavigationBar, on main.dart,
I only get a CircularProgressIndicator and the data does show up.
Have any of you experienced this problem?
Does anyone know why my Listview doesn't show up?
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:ssk_final/addeditpage.dart';
//import 'package:flutter_localizations/flutter_localizations.dart';
List<dynamic> list = [];
class CaesPage extends StatefulWidget {
// CaesPage({Key key}) : super(key: key);
#override
_CaesPageState createState() => _CaesPageState();
Widget build(BuildContext context) {
return Container(
child: Center(
child: Text("Cadastro de Cães"),
),
);
}
}
class _CaesPageState extends State<CaesPage> {
String searchString = "";
Future<List<Caes>> caes;
Future getData() async {
var url = 'http://.../api2.php?opcao=read';
var response = await http.get(Uri.parse(url));
return json.decode(response.body);
}
/*
Future _showMyDialog(id, nome) async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button
builder: (BuildContext context) {
return AlertDialog(
title: Text('Exclusão'),
content: SingleChildScrollView(
child: Column(
children: <Widget>[
Text('Confirma a exclusão de ' + nome + '?'),
],
),
),
actions: <Widget>[
TextButton(
child: Text('Confirma'),
onPressed: () {
setState(() {
var url = 'http://.../api.php?opt=delete';
http.post(Uri.parse(url), body: {
'id': id,
});
});
Navigator.pop(context, true);
},
),
TextButton(
child: Text('Cancelar'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
}
*/
#override
void initState() {
super.initState();
caes = fetchCaes();
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Color.fromRGBO(1, 87, 155, 1),
focusColor: Colors.blue,
foregroundColor: Colors.white,
hoverColor: Colors.green,
splashColor: Colors.tealAccent,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddEditPage(),
),
);
debugPrint('Clicked FloatingActionButton Button');
},
),
body: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Divider(),
//SizedBox(height: 10),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: TextField(
onChanged: (value) {
setState(() {
searchString = value.toLowerCase();
});
},
decoration: const InputDecoration(
//contentPadding: EdgeInsets.symmetric(vertical: 10),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(25.0))),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(25.0)),
),
labelText: 'Pesquisa',
suffixIcon: Icon(Icons.search))),
),
SizedBox(height: 10),
Expanded(
child: FutureBuilder<List<Caes>>(
builder: (context, snapshot) {
if (snapshot.hasData) {
return Center(
child: ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return snapshot.data[index].nome
.toLowerCase()
.contains(searchString)
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new InkWell(
onTap: () {
print(index);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddEditPage(
caes: snapshot.data,
index: index,
),
),
);
},
child: new Container(
child: Column(
children: [
Text(
(snapshot.data[index].nome),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold),
),
Text(
('${snapshot.data[index].microchip}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
('${snapshot.data[index].pedigree}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
(snapshot
.data[index].data_nascimento),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
(snapshot.data[index].sexo),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
Text(
(snapshot.data[index].castrado),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
),
),
],
),
),
),
])
: Container();
},
separatorBuilder: (BuildContext context, int index) {
return snapshot.data[index].nome
.toLowerCase()
.contains(searchString)
? Divider()
: Container();
},
),
);
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
return Center(
child: CircularProgressIndicator(),
);
},
// future: list,
),
),
],
),
);
}
}
class Caes {
final int id;
final String nome;
final int microchip;
final int pedigree;
final String data_nascimento;
final String castrado;
final String sexo;
Caes({
this.id,
this.nome,
this.microchip,
this.pedigree,
this.data_nascimento,
this.castrado,
this.sexo,
});
factory Caes.fromJson(Map<String, dynamic> json) {
return Caes(
id: json['id'],
nome: json['nome'],
microchip: json['microchip'],
pedigree: json['pedigree'],
data_nascimento: json['data_nascimento'],
castrado: json['castrado'],
sexo: json['sexo'],
);
}
}
class Titulos {
Titulos({this.data, this.titulo, this.exposicao});
// non-nullable - assuming the score field is always present
final String data;
final String titulo;
final String exposicao;
factory Titulos.fromJson(Map<String, dynamic> json) {
final data = json['data'] as String;
final titulo = json['titulo'] as String;
final exposicao = json['exposicao'] as String;
return Titulos(data: data, titulo: titulo, exposicao: exposicao);
}
Map<String, dynamic> toJson() {
return {
'data': data,
'titulo': titulo,
'exposicao': exposicao,
};
}
}
Future<List<Caes>> fetchCaes() async {
final response = await http.get(Uri.parse('http://.../api.php?opt=read'));
if (response.statusCode == 200) {
var caesJson = jsonDecode(response.body) as List;
return caesJson.map((caes) => Caes.fromJson(caes)).toList();
} else {
throw Exception('Failed to load Caes');
}
}
Screen
I cant really provide an answer in your list view cause it needs more files to run for me. However I can provide you a nice way to search in a list for items and update it with a text field. You can copy and run the code in the main of a test project to see how it is working.
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final StreamController<List<String>> _exercisesStreamController =
StreamController<List<String>>();
late Stream<List<String>> _exercisesStream;
final List<String> _exercises = [
"Running",
"Swimming",
"Football",
"Basketball",
"Volleyball",
"Karate",
"Ski",
"Snowboard",
"Baseball",
"Running1",
"Swimming1",
"Football1",
"Basketball1",
"Volleyball1",
"Karate1",
"Ski1",
"Snowboard1",
"Baseball1",
"Running2",
"Swimming2",
"Football2",
"Basketball2",
"Volleyball2",
"Karate2",
"Ski2",
"Snowboard2",
"Baseball2",
"Running3",
"Swimming3",
"Football3",
"Basketball3",
"Volleyball3",
"Karate3",
"Ski3",
"Snowboard3",
"Baseball3",
];
#override
void initState() {
super.initState();
_exercisesStreamController.sink.add(_exercises);
_exercisesStream = _exercisesStreamController.stream.asBroadcastStream();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(),
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: Column(
children: [
TextFormField(
maxLines: 1,
style: TextStyle(color: Colors.white),
onChanged: (String value) async {
List<String> temp = List.from(_exercises);
temp.removeWhere((element) =>
!element.toLowerCase().contains(value.toLowerCase()));
_exercisesStreamController.sink.add(temp);
},
decoration: InputDecoration(
prefixIcon: Icon(
Icons.search,
color: Colors.white,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(15.0),
),
contentPadding: EdgeInsets.only(left: 15),
filled: true,
fillColor: Colors.blueGrey,
hintText: "search",
hintStyle: TextStyle(
color: Colors.white,
),
),
),
_listViewWidget()
],
),
),
);
}
Widget _listViewWidget() {
return Expanded(
child: StreamBuilder<List<String>>(
initialData: [],
stream: _exercisesStream,
builder: (context, snapshot) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
color: Colors.blueGrey,
borderRadius: BorderRadius.all(
Radius.circular(15),
),
),
padding: EdgeInsets.all(15),
margin: EdgeInsets.symmetric(vertical: 10),
child: Center(
child: Text(
snapshot.data![index],
style: TextStyle(color: Colors.white),
),
),
);
});
},
),
);
}
}
If you need further instructions i am happy to help.

How to navigate from login to home page with Firebase flutter

In the welcome screen, I have two button which is login and register. For the first time, when i try to login to the login screen, it did not navigate to the Home Page. For the second try, I want to login again, it can't back to the login page (stuck at Welcome Screen). Can anyone help me? Thank you
Welcome Screen Code:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class WelcomeScreen extends StatefulWidget {
#override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
final FirebaseAuth _auth = FirebaseAuth.instance;
navigateToLogin() async {
Navigator.pushReplacementNamed(context, "Login");
}
navigateToRegister() async {
Navigator.pushReplacementNamed(context, "SignUp");
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: <Widget>[
SizedBox(height: 35.0),
Container(
height: 400,
child: Image(
image: AssetImage("assets/girlsave.png"),
fit: BoxFit.contain,
),
),
SizedBox(height: 20),
RichText(
text: TextSpan(
text: 'Welcome to ',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: Colors.orange),
children: <TextSpan>[
TextSpan(
text: 'MONGER!',
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold,
color: Colors.orange))
])),
SizedBox(height: 10.0),
Text(
'Your Personal Money Tracker',
style: TextStyle(color: Colors.black),
),
SizedBox(height: 30.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
padding: EdgeInsets.only(left: 30, right: 30),
onPressed: navigateToLogin,
child: Text(
'LOGIN',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
color: Colors.orange),
SizedBox(width: 20.0),
RaisedButton(
padding: EdgeInsets.only(left: 30, right: 30),
onPressed: navigateToRegister,
child: Text(
'REGISTER',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
color: Colors.orange),
],
),
SizedBox(height: 20.0),
],
),
),
);
}
}
Login Page Code:
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:monger_app/WelcomeScreen/signup.dart';
class LoginPage extends StatefulWidget {
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _email, _password;
checkAuthentification() async {
_auth.authStateChanges().listen((user) {
if (user != null) {
print(user);
Navigator.pushReplacementNamed(context, "/");
}
});
}
#override
void initState() {
super.initState();
this.checkAuthentification();
}
login() async {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
try {
await _auth.signInWithEmailAndPassword(
email: _email, password: _password);
} catch (e) {
showError(e.message);
print(e);
}
}
}
showError(String errormessage) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('ERROR'),
content: Text(errormessage),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'))
],
);
});
}
navigateToSignUp() async {
Navigator.push(context, MaterialPageRoute(builder: (context) => SignUpPage()));
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
brightness: Brightness.light,
backgroundColor: Colors.white,
leading: IconButton(
onPressed: (){
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios,
size: 20,
color: Colors.black,),
),
),
body: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
child: Image(
image: AssetImage("assets/girlsave.png"),
fit: BoxFit.contain,
),
),
Container(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Container(
child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Enter Email';
},
decoration: InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email)),
onSaved: (input) => _email = input),
),
Container(
child: TextFormField(
validator: (input) {
if (input.length < 6)
return 'Provide Minimum 6 Character';
},
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
onSaved: (input) => _password = input),
),
SizedBox(height: 20),
RaisedButton(
padding: EdgeInsets.fromLTRB(70, 10, 70, 10),
onPressed: login,
child: Text('LOGIN',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
color: Colors.orange,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
)
],
),
),
),
GestureDetector(
child: Text('Create an Account?'),
onTap: navigateToSignUp,
)
],
),
),
));
}
}
Sign Up code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class SignUpPage extends StatefulWidget {
#override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
FirebaseAuth _auth = FirebaseAuth.instance;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _username, _email, _password;
checkAuthentication() async {
_auth.authStateChanges().listen((user) async {
if (user != null) {
Navigator.pushReplacementNamed(context, "/");
}
});
}
#override
void initState() {
super.initState();
this.checkAuthentication();
}
signUp() async {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
try {
UserCredential user = await _auth.createUserWithEmailAndPassword(
email: _email, password: _password);
if (user != null) {
// UserUpdateInfo updateuser = UserUpdateInfo();
// updateuser.displayName = _name;
// user.updateProfile(updateuser);
await _auth.currentUser.updateProfile(displayName: _username);
// await Navigator.pushReplacementNamed(context,"/") ;
}
} catch (e) {
showError(e.message);
print(e);
}
}
}
showError(String errormessage) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('ERROR'),
content: Text(errormessage),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'))
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
brightness: Brightness.light,
backgroundColor: Colors.white,
leading: IconButton(
onPressed: (){
Navigator.pop(context);
},
icon: Icon(Icons.arrow_back_ios,
size: 20,
color: Colors.black,),
),
),
body: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
child: Image(
image: AssetImage("assets/girlsave.png"),
fit: BoxFit.contain,
),
),
Container(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Container(
child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Enter Username';
},
decoration: InputDecoration(
labelText: 'Username',
prefixIcon: Icon(Icons.person),
),
onSaved: (input) => _username = input),
),
Container(
child: TextFormField(
validator: (input) {
if (input.isEmpty) return 'Enter Email';
},
decoration: InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email)),
onSaved: (input) => _email = input),
),
Container(
child: TextFormField(
validator: (input) {
if (input.length < 6)
return 'Provide Minimum 6 Character';
},
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: Icon(Icons.lock),
),
obscureText: true,
onSaved: (input) => _password = input),
),
SizedBox(height: 20),
RaisedButton(
padding: EdgeInsets.fromLTRB(70, 10, 70, 10),
onPressed: signUp,
child: Text('SignUp',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold)),
color: Colors.orange,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
)
],
),
),
),
],
),
),
));
}
}
Main Code:
import 'package:flutter/material.dart';
import 'package:monger_app/WelcomeScreen/login.dart';
import 'package:monger_app/WelcomeScreen/signup.dart';
import 'package:monger_app/WelcomeScreen/welcome_screen.dart';
import 'package:monger_app/page/root.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: primary
),
debugShowCheckedModeBanner: false,
home:
WelcomeScreen(),
routes: <String,WidgetBuilder>{
"Login" : (BuildContext context)=>LoginPage(),
"SignUp":(BuildContext context)=>SignUpPage(),
"start":(BuildContext context)=>Root(),
},
);
}
}
HomePage Code
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:monger_app/page/setting.dart';
import 'package:monger_app/theme/colors.dart';
import 'package:animated_bottom_navigation_bar/animated_bottom_navigation_bar.dart';
import 'package:monger_app/page/transaction.dart';
import 'package:monger_app/page/statistics.dart';
import 'package:monger_app/page/account.dart';
import 'package:monger_app/page/record.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Root extends StatefulWidget {
#override
_RootState createState() => _RootState();
}
class _RootState extends State<Root> {
final FirebaseAuth _auth = FirebaseAuth.instance;
User user;
bool isloggedin = false;
checkAuthentification() async {
_auth.authStateChanges().listen((user) {
if (user == null) {
Navigator.of(context).pushReplacementNamed("start");
}
});
}
int pageIndex = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: getBody(),
bottomNavigationBar: getFooter(),
floatingActionButton: FloatingActionButton(
onPressed: (){
setTabs(4);
},
child: Icon(Icons.add, size: 25),
backgroundColor: primary,
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
Widget getBody(){
return IndexedStack(
index: pageIndex,
children: [
Transaction(),
Statistics(),
Account(),
Settings(),
Record()
],
);
}
Widget getFooter(){
List<IconData> iconItems = [
Ionicons.md_bookmarks,
Ionicons.md_stats,
Ionicons.md_wallet,
Ionicons.ios_settings,
];
return AnimatedBottomNavigationBar(
activeColor: primary,
splashColor: secondary,
inactiveColor: Colors.black.withOpacity(0.5),
icons: iconItems,
activeIndex: pageIndex,
gapLocation: GapLocation.center,
notchSmoothness: NotchSmoothness.softEdge,
leftCornerRadius: 10,
iconSize: 25,
rightCornerRadius: 10,
onTap: (index) {
setTabs(index);
});
}
setTabs(index) {
setState(() {
pageIndex = index;
});
}
}
You have this code:
Navigator.pushReplacementNamed(context, "/");
but you do not have the named route "/" registered.
From your code, your Home Page is registered as "start".
So you should update the name of the route to "start" and that should work.
Your updated code should be as below:
Navigator.pushReplacementNamed(context, "start");