'how to load image from php server in flutter? I tried but it shows me late initialization error
I want to show my profile picture which is already saved in my database, while I have fetched name, address etc details from my database but it shows error of late initialization,
late Image _photo ;
if (!jsondata["error"]) {
Shared Preferences preferences = await SharedPreferences.getInstance();
// preferences.setString('user_id', jsondata['uid'] );
controllerName.text = jsondata["user"]["name"];
controllerAddress.text = jsondata["user"]["address"];
controllerContact.text = jsondata["user"]["contact_number"];
setState(() {
_photo = Image.network(jsondata['image']);
});
}
}
Now using here
child: CircleAvatar(
radius: 55,
backgroundColor: Colors.red,
child: _photo != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),
child: _photo,
)
: (_image != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.file(
_image,
width: 100,
height: 100,
fit: BoxFit.fitHeight,
),
)
: Container(
decoration: BoxDecoration(
// color: Colors.grey[200],
borderRadius:
BorderRadius.circular(50)),
width: 100,
height: 100,
child: Icon(
Icons.camera_alt,
// color: Colors.grey[800],
),
)),
),
Solution 1:[1]
The problem is getting data from the shared preference takes some time. But the widget is being rendered before the _photo variable is being initialised even.
You can resolve the issue by first initialising the _photo variable with a placeholder image like Image.asset('/path_to_local_image'); and then you can change it when you get the data from shared preferences.
var _photo= Image.asset('/path_to_local_image');
if (!jsondata["error"]) {
Shared Preferences preferences = await SharedPreferences.getInstance();
// preferences.setString('user_id', jsondata['uid'] );
controllerName.text = jsondata["user"]["name"];
controllerAddress.text = jsondata["user"]["address"];
controllerContact.text = jsondata["user"]["contact_number"];
setState(() {
_photo = Image.network(jsondata['image']);
});
}
}
return CircleAvatar(
radius: 55,
backgroundColor: Colors.red,
child: _photo != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),
child: _photo,
)
: (_image != null
? ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.file(
_image,
width: 100,
height: 100,
fit: BoxFit.fitHeight,
),
)
: Container(
decoration: BoxDecoration(
// color: Colors.grey[200],
borderRadius:
BorderRadius.circular(50)),
width: 100,
height: 100,
child: Icon(
Icons.camera_alt,
// color: Colors.grey[800],
),
)),
),
.............
.......
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Naimul Kabir |
