How to save user data in cloud fire store in flutter - firebase

I am using a package called lit_firebase_auth which makes firebase authentication easier to handle. I want to be able to save user data, such as the username after the user logs in. Basically as such:
User logs in or signs up --> User clicks on edit profile page from the home screen --> User can enter their desired name in the text field and click save --> Saves this data to the cloud of the respectful logged in user.
Please I'm a beginner and I have no idea how to pull this off.
Here is the code for reference:
cloud_firebase.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<void> userSetup(String displayName) async {
CollectionReference users = FirebaseFirestore.instance.collection('Users');
FirebaseAuth auth = FirebaseAuth.instance;
String uid = auth.currentUser.uid.toString();
users.add({'displayName': displayName, 'uid': uid});
return;
}
auth.dart
import 'package:flutter/material.dart';
import 'package:kiwi/screens/auth/register.dart';
import 'package:kiwi/screens/background_painter.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/auth/sign_in.dart';
import 'package:animations/animations.dart';
import 'package:kiwi/screens/home.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const AuthScreen(),
);
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen>
with SingleTickerProviderStateMixin {
AnimationController _controller;
ValueNotifier<bool> showSignInPage = ValueNotifier<bool>(true);
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 2));
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: LitAuth.custom(
onAuthSuccess: () {
Navigator.of(context).pushReplacement(HomeScreen.route);
},
child: Stack(
children: [
SizedBox.expand(
child: CustomPaint(
painter: BackgroundPainter(),
)),
Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: 800),
child: ValueListenableBuilder<bool>(
valueListenable: showSignInPage,
builder: (context, value, child) {
return PageTransitionSwitcher(
reverse: !value,
duration: Duration(milliseconds: 800),
transitionBuilder:
(child, animation, secondaryAnimation) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.vertical,
fillColor: Colors.transparent,
child: child,
);
},
child: value
? SignIn(
key: ValueKey('SignIn'),
onRegisterClicked: () {
context.resetSignInForm();
showSignInPage.value = false;
_controller.forward();
},
)
: Register(
key: ValueKey('Register'),
onSignInPressed: () {
context.resetSignInForm();
showSignInPage.value = true;
_controller.reverse();
},
),
);
},
),
),
),
],
),
),
);
}
}
splash.dart
import 'package:flutter/material.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/home.dart';
import 'package:kiwi/screens/auth/auth.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const SplashScreen(),
);
#override
Widget build(BuildContext context) {
final user = context.watchSignedInUser();
user.map(
(value) {
_navigateToHomeScreen(context);
},
empty: (_) {
_navigateToAuthScreen(context);
},
initializing: (_) {},
);
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
void _navigateToAuthScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(AuthScreen.route),
);
}
void _navigateToHomeScreen(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.of(context).pushReplacement(HomeScreen.route),
);
}
}
edit_profile.dart
import 'package:flutter/material.dart';
import 'package:kiwi/config/palette.dart';
import 'package:kiwi/screens/auth/decoration_functions.dart';
class Profile extends StatefulWidget {
const Profile({Key key}) : super(key: key);
static MaterialPageRoute get route => MaterialPageRoute(
builder: (context) => const Profile(),
);
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
// UserModel _currentUser = locator.get<UserController>().currentUser;
// File _image;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Edit Profile'),
),
body: Builder(
builder: (context) => Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 20.0,
),
Column(
children: <Widget>[
Text(
'Hey there',
style: TextStyle(color: Palette.lightGreen, fontSize: 20),
)
],
),
SizedBox(
height: 20,
),
Expanded(
flex: 8,
child: ListView(
children: [
Padding(
padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
child: TextFormField(
style: const TextStyle(
fontSize: 18,
color: Colors.green,
),
decoration: signInInputDecoration(
hintText: 'New Username',
),
),
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
elevation: 4,
color: Colors.red,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Cancel',
style: TextStyle(color: Colors.white),
),
),
RaisedButton(
elevation: 4,
color: Palette.lightGreen,
onPressed: () {
Navigator.of(context).pop();
},
child: const Text(
'Save',
style: TextStyle(color: Colors.white),
),
),
],
),
],
),
),
],
),
),
),
);
}
}

to save user data to document in firebase using uuid for document name the below code will work.
if you are confused about how to use the code in your app its simple.
just follow the steps:
call userSetup Function from onpress while passing the display name data.
how to use
the below code will create new document using the currect users uuid in firestore in user collection and save the data.
onPress:(){
userSetup(displayName:"zakriakhan");
}
userSteup Function
Future<void> userSetup(String displayName) async {
//firebase auth instance to get uuid of user
FirebaseAuth auth = FirebaseAuth.instance.currentUser();
//now below I am getting an instance of firebaseiestore then getting the user collection
//now I am creating the document if not already exist and setting the data.
FirebaseFirestore.instance.collection('Users').document(auth.uid).setData(
{
'displayName': displayName, 'uid': uid
})
return;
}

Related

error: Undefined name 'uploadTask'. Flutter error

I am integrating file uploading system in my flutter project using firebase.
While making progress indicator I am getting undefined name 'uploadTask' error.
In this project we can upload file,image and many more to firebase and simultaneously view at the same time.
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future selectFile() async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
setState(() {
pickedFile = result.files.first;
});
}
Future uploadFile() async {
final path = 'files/${pickedFile!.name}';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
uploadTask = ref.putFile(file);
final snapshot = await uploadTask!.whenComplete(() => null);
final urlDownload = await snapshot.ref.getDownloadURL();
print('Download link: $urlDownload');
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
if (pickedFile != null)
Expanded(
child: Container(
color: Colors.blue[100],
child: Center(
child: Image.file(
File(pickedFile!.path!),
width: double.infinity,
fit: BoxFit.cover,
),
),
),
),
SizedBox(
height: 32,
),
ElevatedButton(
onPressed: selectFile,
child: const Text(
'Select File',
),
),
ElevatedButton(
onPressed: uploadFile,
child: const Text(
'Upload File',
),
),
buildProgress(),
],
),
),
),
);
}
}
Widget buildProgress() => StreamBuilder<TaskSnapshot>(
stream: uploadTask?.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data!;
double progress = data.bytesTransferred / data.totalBytes;
return SizedBox(
height: 50,
child: Stack(
fit: StackFit.expand,
children: [
LinearProgressIndicator(
value: progress,
backgroundColor: Colors.grey,
color: Colors.green,
),
Center(
child: Text(
'${(100 * progress).roundToDouble()}%',
style: const TextStyle(color: Colors.white),
),
)
],
),
);
} else {
return const SizedBox(
height: 50,
);
}
},
);

Edit User Profile Page and Profile Picture. Using Real-Time Database flutter

I am trying to pull user data from my UserProfileBrowse Data model and display it on my user profile edit page. Including the image. I also want to update the data into my real-time Database.
THIS IS MY DATA MODEL
class UserProfileBrowse {
String userId;
int age;
String name;
String email;
String imageUrl;
UserProfileBrowse(
this.userId,
this.age,
this.name,
this.email,
this.imageUrl,
);
Map<dynamic, dynamic> toJson() => <dynamic, dynamic>{
'userId': userId,
'age': age,
'name': name,
'email': email,
'imageUrl' : imageUrl,
};
}
THIS IS MY USER PROFILE EDIT PAGE
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/auth.dart';
import 'home.dart';
import 'settings.dart';
import 'package:shadow_app_project/data_models/user_profile_browse.dart';
import 'package:shadow_app_project/image_selection/user_edit_image.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
class SettingsUI extends StatelessWidget {
const SettingsUI({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: "Setting UI",
home: EditProfilePage(),
);
}
}
class EditProfilePage extends StatefulWidget {
const EditProfilePage({Key? key}) : super(key: key);
#override
_EditProfilePageState createState() => _EditProfilePageState();
}
class _EditProfilePageState extends State<EditProfilePage> {
String currentUser = (Auth().auth.currentUser as User).email.toString();
TextEditingController displayNameController = TextEditingController();
TextEditingController ageController = TextEditingController();
bool isLoading = false;
User? user;
UserProfileBrowse? userModel;
String? imageUrl;
final refDatabase = FirebaseDatabase.instance;
bool showPassword = false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
elevation: 1,
leading: IconButton(
icon: const Icon(
Icons.arrow_back,
color: Colors.green,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => const SettingsPage()));
},
),
actions: [
IconButton(
icon: const Icon(
Icons.settings,
color: Colors.green,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => const SettingsPage()));
},
),
],
),
body: Container(
padding: const EdgeInsets.only(left: 16, top: 25, right: 16),
child: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: ListView(
children: [
const Text(
"Edit Profile",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
const SizedBox(
height: 15,
),
Container(
width: 130,
height: 130,
decoration: BoxDecoration(
border: Border.all(
width: 4,
color: Theme.of(context).scaffoldBackgroundColor),
boxShadow: [
BoxShadow(
spreadRadius: 2,
blurRadius: 10,
color: Colors.black.withOpacity(0.1),
offset: const Offset(0, 10))
],
shape: BoxShape.circle,
image: const DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
"https://images.pexels.com/photos/3307758/pexels-photo-3307758.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=250",
))),
),
const SizedBox(
height: 35,
),
TextField(
decoration: const InputDecoration(
labelText: "Name",
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal)),
hintText: 'Input Name',
),
controller: displayNameController,
keyboardType: TextInputType.name,
),
TextField(
decoration: const InputDecoration(
labelText: "Age",
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal)),
hintText: 'Input Age',
),
controller: ageController,
//
keyboardType: TextInputType.number,
),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text("Email: ", style: TextStyle(fontSize: 20),),
),
const SizedBox(
height: 35,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed: () {},
child: const Text("CANCEL",
style: TextStyle(
fontSize: 14,
letterSpacing: 2.2,
color: Colors.black)),
),
TextButton(
onPressed: () {
FirebaseDatabase.instance.ref()
.child('useProfileBrowse')
.child(user!.uid)
.update({
'name': displayNameController.text //yes I know.
});
FirebaseDatabase.instance.ref()
.child('useProfileBrowse')
.child(user!.uid)
.update({
'age': ageController.text //yes I know.
});
},
child: const Text(
"SAVE",
style: TextStyle(
fontSize: 14,
letterSpacing: 2.2,
color: Colors.white),
),
)
],
)
],
),
),
),
);
}
}
I am thinking to use a StreamBuilder in my body: with stream: FirebaseDatabase.instance.ref().child('userProfileBrowse').child(user!.uid).onValue,
Any idea how can I display User profile Imageurl, name, and age from my real-time Database
And also edit the information using stream builder or any other method
I have just coded the UI for my profile edit page. I just want someone to help me retrieve data from my data model class and display it on my user edit page. A single line to display just a name from my data model will help a lot to understand how retrieving data works. I have already saved data(imageUrl, name, age) into my data models during the signup process. Just want to display it
full example with StreamProvider :
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Person {
Person({required this.name, required this.initialAge});
final String name;
final int initialAge;
Stream<String> get age async* {
var i = initialAge;
while (i < 85) {
await Future.delayed(const Duration(seconds: 1), () {
i++;
});
yield i.toString();
}
}
}
void main() {
runApp(
StreamProvider<String>(
create: (_) => Person(name: 'Yohan', initialAge: 25).age,
initialData: 25.toString(),
catchError: (_, error) => error.toString(),
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Future Provider"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Consumer<String>(
builder: (context, String age, child) {
return Column(
children: <Widget>[
const Text("Watch Yohan Age..."),
const Text("name: Yohan"),
Text("age: $age"),
],
);
},
),
),
),
);
}
}
You already started to use the Provider as a state management, so I'd recommend using StreamProvider like this:
StreamProvider<String>(
create: (_) => Profile(name: 'Yohan', initialImageURL: ''),
initialData: ''.toString(),
catchError: (_, error) => error.toString(),
child: child(),
builder: (context) {
// Pretend this is loading data and reporting the percent loaded.
},
),
)
or you can just notify the UI every time you have got a change from the firebase using ChangeNotifier,
for examples, visit Docs

Firebase : Why appearing [clound_firestore/permission-denied] for my firestore

I know there is a lot of similar posts, but I still cannot find my own answer for my issue. Since I want to get the data from firebase without pressing the button and diretly can get the data from it, therefore I have used the StreamBuilder for my coding but I still get this error. Is this is my firestore database or realtime database permission get any wrong?
--Issue warning--
Below are my coding:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:profile_staff/edit_profile_page.dart';
import 'package:profile_staff/profile_widget.dart';
import 'package:profile_staff/user.dart';
import 'package:profile_staff/user_preferences.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
final Stream<QuerySnapshot> users =
FirebaseFirestore.instance.collection('users').snapshots();
TextEditingController _controller = TextEditingController();
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
final user = UserPreferences.myUser;
return Scaffold(
appBar: AppBar(
leading: new IconButton(
onPressed: () {}, icon: new Icon(Icons.arrow_back_ios_sharp)),
title: Center(
child: Text(
'My Profile',
style: TextStyle(color: Colors.white),
),
),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => EditProfilePage()),
);
},
icon: new Icon(Icons.create_outlined))
],
backgroundColor: Colors.green,
shadowColor: Colors.white,
elevation: 3,
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Read Data',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
),
Container(
height: 250,
padding: const EdgeInsets.symmetric(vertical: 20),
child: StreamBuilder<QuerySnapshot>(
stream: users,
builder: (
BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot,
) {
// if (!snapshot.hasData) {
// return Text('error404');
// }
if (snapshot.connectionState == ConnectionState.waiting) {
return Text('Loading');
}
final data = snapshot.requireData;
return ListView.builder(
itemCount: data.size,
itemBuilder: (context, index) {
return Text(
'My name is ${data.docs[index]['name']} and I am ${data.docs[index]['age']}');
},
);
},
))
],
),
}
My Firestore Database:
My Realtime Database:
enter image description here
enter image description here
I was facing same issue.Forgot to deploy/upload new rules

Download image to phone directory

I've created a flutter project that show a staggeredgridview of images from firestore database. Once i click on one of the images it shows that image. What i want is a download button thats saves the image to my device. Ath the moment I've just used pop.
I've read some about the path provider package but i can't figure out how to implement this in the code. Perhaps there is a better solution?
StaggeredGridView Page
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:proj/screens/home/instafull.dart';
import 'dart:async';
import 'package:proj/services/auth.dart';
import 'package:proj/shared/constants.dart';
class Instapage extends StatefulWidget {
#override
_InstapageState createState() => _InstapageState();
}
class _InstapageState extends State<Instapage> {
final AuthService _auth = AuthService();
StreamSubscription<QuerySnapshot> subscription;
List<DocumentSnapshot> wallpaperlist;
final CollectionReference collectionReference = FirebaseFirestore.instance.collection('mediapost');
#override
void initState() {
// TODO: implement initState
super.initState();
subscription = collectionReference.snapshots().listen((datasnapshot) {
setState(() {
wallpaperlist = datasnapshot.docs;
});
});
}
#override
void dispose() {
subscription?.cancel();
// TODO: implement dispose
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: bas,
body: wallpaperlist != null?
StaggeredGridView.countBuilder(
padding: const EdgeInsets.fromLTRB(10, 8, 10, 0),
crossAxisCount: 4,
itemCount: wallpaperlist.length,
itemBuilder: (context, index){
String imgPath = wallpaperlist[index].get('img');
return new Material(
elevation: 8,
borderRadius: BorderRadius.all(Radius.circular(8.0)),
child: InkWell(
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => InstaFull(imgPath: imgPath))),
child: Hero(
tag: imgPath,
child: FadeInImage(
image: NetworkImage(imgPath),
fit: BoxFit.cover,
placeholder: AssetImage('assets/wally2.jpg'),
),
),
),
);
},
staggeredTileBuilder: (index) => StaggeredTile.count(2, index.isEven?2:3),
mainAxisSpacing: 8,
crossAxisSpacing: 8,
): Center(
child: CircularProgressIndicator(),
),
);
}
}
Picture Page
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class InstaFull extends StatelessWidget {
String imgPath;
InstaFull({this.imgPath});
final LinearGradient backgroundGradient = LinearGradient(
colors: [Color(0x10000000), Color(0x30000000)],
begin: Alignment.topLeft,end: Alignment.bottomRight);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox.expand(
child: Stack(
children: [
Align(
alignment: Alignment.center,
child: Hero(
tag: imgPath,
child: Image.network(imgPath),
),
),
Align(
alignment: Alignment.topCenter,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
leading: IconButton(
icon: Icon(Icons.close,
color: Colors.black,
),
onPressed: () => Navigator.of(context).pop(),
),
),
],
),
),
Align(
alignment: Alignment.bottomCenter,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Download')),
],),
)
],
),
),
);
}
}
You can use gallery_saver
Install it and enable this permissions:
iOS
Add the following keys to your Info.plist file, located in <project root>/ios/Runner/Info.plist:
NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
Android
Android
android.permission.WRITE_EXTERNAL_STORAGE - Permission for usage of external storage
Official example of gallery_saver:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String firstButtonText = 'Take photo';
String secondButtonText = 'Record video';
double textSize = 20;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
color: Colors.white,
child: Column(
children: <Widget>[
Flexible(
flex: 1,
child: Container(
child: SizedBox.expand(
child: RaisedButton(
color: Colors.blue,
onPressed: _takePhoto,
child: Text(firstButtonText,
style:
TextStyle(fontSize: textSize, color: Colors.white)),
),
),
),
),
Flexible(
child: Container(
child: SizedBox.expand(
child: RaisedButton(
color: Colors.white,
onPressed: _recordVideo,
child: Text(secondButtonText,
style: TextStyle(
fontSize: textSize, color: Colors.blueGrey)),
),
)),
flex: 1,
)
],
),
),
));
}
void _takePhoto() async {
ImagePicker.pickImage(source: ImageSource.camera)
.then((File recordedImage) {
if (recordedImage != null && recordedImage.path != null) {
setState(() {
firstButtonText = 'saving in progress...';
});
GallerySaver.saveImage(recordedImage.path).then((String path) {
setState(() {
firstButtonText = 'image saved!';
});
});
}
});
}
void _recordVideo() async {
ImagePicker.pickVideo(source: ImageSource.camera)
.then((File recordedVideo) {
if (recordedVideo != null && recordedVideo.path != null) {
setState(() {
secondButtonText = 'saving in progress...';
});
GallerySaver.saveVideo(recordedVideo.path).then((String path) {
setState(() {
secondButtonText = 'video saved!';
});
});
}
});
}
void _saveNetworkVideo() async {
String path =
'https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4';
GallerySaver.saveVideo(path).then((bool success) {
setState(() {
print('Video is saved');
});
});
}
void _saveNetworkImage() async {
String path =
'https://image.shutterstock.com/image-photo/montreal-canada-july-11-2019-600w-1450023539.jpg';
GallerySaver.saveImage(path).then((bool success) {
setState(() {
print('Image is saved');
});
});
}
}

Read data from Firebase database and display the details as the widget loads

In my flutter project, I want to read data from the Firebase Database of the current user logged in and display the User name from the database and display at the appbar[Line 43:title: Text('$userName'),] of the Page.I had tried by the following code below but it gives error on line 26[Line:final FirebaseUser user = _auth.currentUser();]. The error is on the keyword '_auth.currentUser()'
Error is:A value of type 'Future' can't be assigned to a variable of type 'FirebaseUser'
Here is the code:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:udharibook/Screens/UserProfile.dart';
import 'package:udharibook/services/authservice.dart';
import 'Customer_Support.dart';
import 'package:udharibook/services/UserData.dart';
class DashboardPage extends StatefulWidget {
#override
_DashboardPageState createState() => _DashboardPageState();
}
class _DashboardPageState extends State<DashboardPage> {
List<UserData> userdata = [];
String userName;
#override
void initState()
{
super.initState();
FirebaseAuth _auth = FirebaseAuth.instance;
DatabaseReference DBRef = FirebaseDatabase.instance.reference().child('Users');
final FirebaseUser user = _auth.currentUser();
DBRef.child(user.uid).once().then((DataSnapshot user)
{
userName = user.value['Name'];
setState(() {
print(userName);
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('$userName'),
backgroundColor: Color.fromRGBO(162, 42, 43, 1.0),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
print("Search Clicked");
}),
IconButton(
icon: Icon(Icons.sort),
onPressed: () {
print("Sort Clicked");
}),
],
),
drawer: Drawer(
child: ListView(
children: <Widget>[
DrawerHeader(
child: Text("mehul jain"),
decoration: BoxDecoration(
color: Color.fromRGBO(162, 42, 43, 1.0),
),
),
CustomMenu(
Icons.person,
'Profile',() => {
Navigator.pop(context),
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => UserProfile()))
}),
CustomMenu(Icons.assessment, 'Reports', () => {}),
CustomMenu(Icons.settings, 'Settings', () => {}),
CustomMenu(
Icons.perm_phone_msg,
'Customer Support',
() => {
Navigator.pop(context),
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => CustSupport()))
}),
CustomMenu(Icons.lock, 'Log Out', () => {AuthService().signOut()}),
],
),
),
);
}
}
class CustomMenu extends StatelessWidget {
IconData icon;
String text;
Function onTap;
CustomMenu(this.icon, this.text, this.onTap);
#override
Widget build(BuildContext context) {
// TODO: implement build
return Padding(
padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 0.0),
child: Container(
decoration: BoxDecoration(
border:
Border(bottom: BorderSide(color: Colors.grey.shade400))),
child: InkWell(
splashColor: Colors.redAccent,
onTap: onTap,
child: Container(
height: 60.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(icon),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
text,
style: TextStyle(
fontSize: 17.0, fontFamily: 'Exo2'),
)),
],
),
Icon(Icons.arrow_right),
],
),
))));
}
}
currentUser() returns a Future<FirebaseUser>, therefore you have to do the following:
_auth.currentUser().then((curUser)
{
DBRef.child(curUser.uid).once().then((DataSnapshot user)
{
userName = user.value['Name'];
setState(() {
print(userName);
});
});
});
https://dart.dev/codelabs/async-await

Resources