I am getting imageUrl from another page. and I want to use the "imageUrl" inside of "theimage" but I cannot access it. I am facing this error.
The instance member 'widget' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression
class ProductCard extends StatefulWidget {
final String imageUrl;
ProductCard(
{this.imageUrl,});
#override
State<ProductCard> createState() => _ProductCardState();
}
class _ProductCardState extends State<ProductCard> {
// I can not access widget.imageUrl in here
final theImage = Image.network("${widget.imageUrl}", fit: BoxFit.cover);
/// Did Change Dependencies
#override
void didChangeDependencies() {
precacheImage(theImage.image, context);
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
return Container(
child:theImage;
);
}
}
You are using named constructor ProductCard make imageUrl required nullable ,or provide default value.
const ProductCard(
{required this.imageUrl,});
And use initState for initialization.
late final Image theImage;
#override
void initState() {
theImage = Image.network("${widget.imageUrl}", fit: BoxFit.cover);
super.initState();
}
Next remove ; from end of theImage or use ,.
#override
Widget build(BuildContext context) {
return Container(child: theImage);
}
Related
Hi I'am new to Flutter making an app for booking appointments which require to screens for two types of users i.e. patient and doctor.
class DashboardPage extends StatefulWidget {
#override
_DashboardPageState createState() => _DashboardPageState();
}
class _DashboardPageState extends State<DashboardPage> {
UserProvider userProvider;
final AuthMethods _authMethods = AuthMethods();
#override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_) async {
userProvider = Provider.of<UserProvider>(context, listen: false);
await userProvider.refreshUser();
_authMethods. getUserDetails();
});
}
User user = User();
#override
Widget build(BuildContext context) {
if (user.role == 'patient') {
return PatientHomePage();
}
else if (user.role == 'doctor') {
return DoctorHomePage();}
return Container(color: Colors.red,);
}
}
role variable is defined in another dart file:
class User { String uid; String name; String email; String role = "patient"; String profilePhoto; User({ this.uid, this.name, this.email, this.role, this.profilePhoto, }); ........... }
the default value "patient" is assigned to it when a user logs in. Future<void> addDataToDb(FirebaseUser currentUser) async { User user = User( uid: currentUser.uid, email: currentUser.email, name: currentUser.displayName, profilePhoto: currentUser.photoUrl, role: "patient"); firestore .collection(USERS_COLLECTION) .document(currentUser.uid) .setData(user.toMap(user)); } all this is happening in another dart file
But this logic is not working as expected as it's showing only the red screen on phone which implies that
there is some issue in getting user.role from firebase.
Please help me...
class DashboardPage extends StatefulWidget {
#override
_DashboardPageState createState() => _DashboardPageState();
}
class _DashboardPageState extends State<DashboardPage> {
UserProvider userProvider;
final AuthMethods _authMethods = AuthMethods();
User user = User();
#override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_) async {
userProvider = Provider.of<UserProvider>(context, listen: false);
/// This method is future method so it might happen that after widget render you are getting response.
await userProvider.refreshUser();
/// seState will rebuild your widget with new user details
setState(() {
user = _authMethods. getUserDetails();
});
});
}
#override
Widget build(BuildContext context) {
if (user.role == 'patient') {
return PatientHomePage();
}
else if (user.role == 'doctor') {
return DoctorHomePage();}
return Container(color: Colors.red,);
}
}
Future<List> getHistory() async {
List images;
final List<DocumentSnapshot> documents =
(await Firestore.instance.collection("History").getDocuments()).documents;
images = documents.map((documentSnapshot) => documentSnapshot['images']).toList();
return images;
}
Hi all, what am I doing wrong here, it never returns images. I am sure that I am not doing this the correct way so any hints would be greatly appreciated.
class _HomeScreenState extends State<HomePage> {
#override
void initState() {
super.initState();
getHistory();
}
Thank you
You're returning the images but not doing anything with the return value, Try this:
class _HomeScreenState extends State<HomePage> {
List images;
Future<List> getHistory() async {
final List<DocumentSnapshot> documents = (await
Firestore.instance.collection("History").getDocuments()).documents;
images = documents.map((documentSnapshot) => documentSnapshot['images']).toList();
}
#override
void initState() {
super.initState();
getHistory();
}
And in the widget tree use a future builder that awaits getHistory()'s results
I have a FirebaseActions class which is doing signup and signin works for me. I added a getCurrentUser method in it. I'm calling that function from my HomeScreen widget. I need to put the returned value(type= FirebaseUser) into a variable in my HomeScreen to reach loggedInUser.email. But I get this error. My question; is there any way to get a FirebaseUser type data into a Future type variable? When I write this function in HomeScreen instead of FirebasAction class, it works but is it the best practice?
FirebaseActions class
static getCurrentUser(context) async {
final user = await _auth.currentUser().catchError((error) {
Scaffold.of(context).showSnackBar(AppSnackBar.appSnackBar(error.message));
});
if (user != null) {
return user;
}
}
HomeScreen widget
class _HomeScreenState extends State<HomeScreen> {
FirebaseUser loggedInUser;
#override
void initState() {
super.initState();
loggedInUser = FirebaseActions.getCurrentUser(context);
print(loggedInUser.toString());
}
You are getting this error because you didn't specify a return type in your getCurrentUser() function.
Replace your code with the one below and everything will work fine.
To solve this issue:
Check the code below: It works perfectly fine:
Firebase Action Class
// give your function a return type
static Future<FirebaseUser> getCurrentUser(context) async {
final user = await _auth.currentUser().catchError((error) {
Scaffold.of(context).showSnackBar(AppSnackBar.appSnackBar(error.message));
});
if (user != null) {
return user;
}
}
Home Screen Widget
class _HomeScreenState extends State<HomeScreen> {
FirebaseUser loggedInUser;
#override
void initState() {
super.initState();
call the function here
logInUser();
print(loggedInUser.toString());
}
I hope this helps
UPDATE
// create a new function to log in user
void logInUser() async {
// await the result because you are invoking a future method
loggedInUser = await FirebaseActions.getCurrentUser(context);
}
You are not specified return type of method and also method is async, so you have to put await where you are calling.
static Future<FirebaseUser> getCurrentUser(context) async {
also, add await where you are calling.
loggedInUser = await FirebaseActions.getCurrentUser(context);
update:
create new function and call in that function.
callme() async{
loggedInUser = FirebaseActions.getCurrentUser(context);
print(loggedInUser.toString());
}
initstate:
#override
void initState() {
super.initState();
callme();
}
Here's how I handle async functions in my initstate:
FirebaseActions.getCurrentUser(context).then((val){loggedInUser = val});
Also make sure you specify the return type in your asynchronous function.
Future<FirebaseUser> getCurrentUser(context) async {...
i'm trying to make a singleton class from MyDatabase with default constructor to access to getUserDao on this class, implemented code work fine but i have some other issue with that as
i have to use async and await in outside of class
i have to use that
only on main function because main method should be async
for example:
my singleton class:
class MydbModel {
UserDao _userDao;
MydbModel._(this._userDao);
static Future<MydbModel> create() async => MydbModel._(await initialDatabase());
static Future<UserDao> initialDatabase() async {
var db = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
return db.userDao;
}
UserDao get userDao=>_userDao;
}
and main class:
main() async {
var mydbModel = await MydbModel.create();
print(mydbModel.userDao);
}
i have to define that only on main method and i can't use that on StatefulWidget or State<Classname classes and when i try to use this instance i have to pass it for all class
how can i resolve this problem to use simply class in all part of application?
for example:
main() {
var userDao = MydbModel.create().then((dao){
return dao;
});
print(userDao);
}
Try this:
class MydbModel {
static UserDao _userDao;
MydbModel._();
static UserDao get userDao =>_userDao;
static Future<void> create() async => _userDao = await initialDatabase();
static Future<UserDao> initialDatabase() async {
var db = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
return db.userDao;
}
}
You should be able to access _userDao from anywhere using MydbModel.userDao.
If your app requires data to be loaded asynchronously before being ready for user input, you'll have to show some UI while it loads. FutureBuilder handles such a case.
Here's an example that shows a spinner until prepareData is finished. Another option would be to show a splash screen.
Future prepareData() async => null;
...
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: prepareData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('${snapshot.data}');
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
} else
return Center(child: CircularProgressIndicator());
},
);
}
I want to declare a user object, that I will instantiate with an http request, and I want it to be global. How can I do it? With a Singleton? But how can I make this class also a Singleton? Or is there another way?
That is what I've done so far:
class User{
String username;
String password;
int id;
User({this.username, this.id});
factory User.fromJson(Map<String, dynamic> json){
return User(
username: json['name'],
id: json['id']
);
}
}
and then:
var user = await login(username, password, context);
In flutter, you should not make singletons. Instead, you should store it into a widget that exposes these data to all of its descendants.
Usually InheritedWidget
The reason being, with such architecture all the descendants are automatically aware of any change made to your "singleton".
A typical example would be the following:
#immutable
class User {
final String name;
User({this.name});
}
class Authentificator extends StatefulWidget {
static User currentUser(BuildContext context) {
final _AuthentificatorScope scope = context.inheritFromWidgetOfExactType(_AuthentificatorScope);
return scope.user;
}
final Widget child;
Authentificator({this.child, Key key}): super(key: key);
#override
_AuthentificatorState createState() => _AuthentificatorState();
}
class _AuthentificatorState extends State<Authentificator> {
#override
Widget build(BuildContext context) {
return _AuthentificatorScope(
child: widget.child,
);
}
}
class _AuthentificatorScope extends InheritedWidget {
final User user;
_AuthentificatorScope({this.user, Widget child, Key key}) : super(child: child, key: key);
#override
bool updateShouldNotify(_AuthentificatorScope oldWidget) {
return user != oldWidget.user;
}
}
which you have to instantiate like this:
new MaterialApp(
title: 'Flutter Demo',
builder: (context, child) {
return Authentificator(
child: child,
);
},
home: Home(),
);
and then use inside your pages like this:
#override
Widget build(BuildContext context) {
User user = Authentificator.currentUser(context);
...
}