After i have created the sign in and signup in flutter and i have connect it to firebase, i added a textfield for the name of the user. So if the user register his name also will be stored, then this data is saved into firebase with the id of the user. The problem is when i try to fetch this data my these method it gives me null ,
This is the way how i am fetching the data of the user :
class WelcomePage extends StatefulWidget {
String email;
WelcomePage ({Key? key, required this.email}) : super(key: key);
#override
State<WelcomePage> createState() => _WelcomePageState();
}
class _WelcomePageState extends State<WelcomePage> {
ScrollController? _scrollcontroller;
final FirebaseAuth _auth =FirebaseAuth.instance;
String? _name ;
String? _uid;
#override
void initState() {
super.initState();
_scrollcontroller = ScrollController();
_scrollcontroller?.addListener(() {
setState(() {});
});
getData();
}
void getData() async{
User? user = _auth.currentUser;
_uid = user!.uid;
final DocumentSnapshot userDoc =
await FirebaseFirestore.instance.collection('users').doc(user.uid).get();
_name = userDoc.get('name');
}
Related
How to solve this error?
The named parameter 'key' is required, but there's no corresponding argument. (Documentation) Try adding the required argument.
error
Future<void> onJoin() async {
// update input validation
setState(() {
_channelController.text.isEmpty
? _validateError = true
: _validateError = false;
});
if (_channelController.text.isNotEmpty) {
await _handleCameraAndMic(Permission.camera);
await _handleCameraAndMic(Permission.microphone);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoCall(
channelName: _channelController.text,
role: _role,
),
),
);
}
}
class VideoCall
class VideoCall extends StatefulWidget {
final String channelName;
final ClientRole role;
const VideoCall({Key key, required this.channelName, required this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}
class _VideoCallState extends State<VideoCall> {
final _users = <int>[];
final _infoStrings = <String>[];
bool muted = false;
late RtcEngine _engine;
#override
void dispose() {
// clear users
_users.clear();
// destroy sdk
_engine.leaveChannel();
_engine.destroy();
super.dispose();
}
#override
void initState() {
super.initState();
// initialize agora sdk
initialize();
}
this is the videoCall class in there no any error shows.
when add "key" show this
When remove required property from key in video call class
show this error
In VideoCall class, key property set as a required, change it to optional:
class VideoCall extends StatefulWidget {
final String? channelName;
final ClientRole? role;
const VideoCall({Key? key, this.channelName, this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}
Am trying to achieve app that if person logged in the response of app is sent to another screen. here it is asking to add the same details in splash screen, am using shared preferences to see the user is logged in or not. how can we fix this issue.
splash.dart
#override
void initState() {
super.initState();
// navigate();
getValidationData().whenComplete(() async {
Future.delayed(const Duration(seconds: 6), () {
PageNavigator(ctx: context).nextPageOnly(
page: finalEmail == null ? const LoginPage() : const HomeScreen(// what to do here));
});
});
}
login.dart
///Save users data and then navigate to homepage
final int userId = res['userId'];
final String token = res['token'];
final bool recharge = res['recharge'];
final String name = res['name'];
PageNavigator(ctx: context).nextPageOnly(
page: HomeScreen(
userId: userId,
token: token,
recharge: recharge,
name: name,
));
home.dart
class HomeScreen extends StatefulWidget {
final int userId;
final String token;
final bool recharge;
final String name;
const HomeScreen({
Key? key,
required this.userId,
required this.token,
required this.recharge,
required this.name,
}) : super(key: key);
I got the error LateInitializationError: Field 'authProvider' has not been initialized. for the following:
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
#override
State createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
final FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
final ScrollController listScrollController = ScrollController();
late AuthProvider authProvider;
String? currentUserId;
late MainProvider mainProvider;
Debouncer searchDebouncer = Debouncer();
StreamController<bool> btnClearController = StreamController<bool>();
TextEditingController searchBarTec = TextEditingController();
#override
void initState() {
super.initState();
mainProvider = context.read<MainProvider>();
if (authProvider.getUserFirebaseId()!.isNotEmpty == true) {
currentUserId = authProvider.getUserFirebaseId()!;
} else {
return null;
}
registerNotification();
listScrollController.addListener(scrollListener);
}
//more code below
This code is from a Demo: Chat App with Flutter
How do I initialize the fields for authProvider, mainProvider etc?
Late initialization error means that a variable marked as late (in your case authProvider) was not initialized before it was accessed.
on a widget the first thing you execute is the constructor and then you execute the initstate. your constructor has nothing and initstate reads authProvider.getUserFirebaseId().
If you take a look at the video's github page, you will see that before calling authProvider, they initialize it by running the following line:
authProvider = context.read<AuthProvider>();
homeProvider = context.read<HomeProvider>();
If you are following a tutorial, the tutorial is either outdated or not complete if it has this sort of error.
I am trying to develop login checker. The following code should redirect to HomeScreen when user is loggedin and to LoginPage in User is not loggedin. But it only gets redirect to LoginScreen() not to HomeScreen() even though it's already logged in.
User Model:
class User {
User({
required this.id,
required this.name,
required this.email,
required this.cart,
});
String id;
String name;
String email;
List cart;
}
UserController:
class UserController extends GetxController {
RxString id = ''.obs;
RxBool isLoggedIn = false.obs;
RxString name = ''.obs;
RxString email = ''.obs;
RxString image = ''.obs;
RxList cart = [].obs;
final NetworkHandler _handler = NetworkHandler();
#override
void onInit() {
super.onInit();
getUserDetails();
}
getUserDetails() {
User _user = _handler.userDetails();
id.value = _user.id;
if (id.value != '') {
isLoggedIn.value = true;
}
name.value = _user.name;
}
}
Checker Screen
class StateCheck extends StatelessWidget {
var controller = Get.put(UserController());
StateCheck({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Obx(
() => controller.isLoggedIn.value
? const HomeScreen()
: const LoginScreen(),
);
}
}
First you have to set login value in SharedPreferences.
when login success
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("isLogin", true);
log out
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("isLogin", false);
You can Check login state || check this in splash screen for best practice (inside init method)
if(prefs.getBool('isLogin')==null||prefs.getBool('isLogin')==false){
// login screen
}else{
// home screen
}
I want to save a variable's value that changes every 5 seconds then read it. I have already tried saving it to shared preferences then reading it but the problem with that was that the value was only saved one time and did not save the changes done to the variable. Is there a way to implement that in flutter?
class _MyAppState extends State<MyApp> {
void initState() {
super.initState();
Future.delayed(Duration.zero, () {
_connect();
});
}
...
void predict(List<double> v) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<List<double>> L=List<List<double>>.filled(1, [0], growable: true);
L[0]=v;
...
String res=response.body;
Map R = json.decode(res);
var _list = R.values.toList();
print(res);
Proba= double.parse(_list[1]);
await prefs.setDouble('Proba', Proba);
}
....
class Page extends StatefulWidget {
Page({Key key, this.title}) : super(key: key);
final String title;
#override
PageState createState() => PageState();
}
class PageState extends State<Page> {
.....
Future<double> _getProbaFromSharedPref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getDouble("Proba") ?? 0;
}
#override
void initState() {
super.initState();
Location1=_getCurrentLocation();
_getStringFromSharedPref();
_getProbaFromSharedPref().then((s) {
Value = s;
});
Future.delayed(Duration.zero, () {
_check();
});
}
}
In the code I tried saving the variable in sharedPreferences then reading it, but I have no clue on how to reload it everytime it changes.