flutter) There's a problem with using imagePicker - flutter

I'm using sdk 2.12.0 and image_picker 0.8.4 version.
I'm going to link my gallery to get an image.
However, when I press the Add Image button on my app, the app turns off immediately.
This is the code for the image_picker I used.
class CreatePage extends StatefulWidget {
const CreatePage({Key? key, required this.user}) : super(key: key);
final User user;
#override
_CreatePageState createState() => _CreatePageState();
}
class _CreatePageState extends State<CreatePage> {
//ImagePicker
final ImagePicker _picker = ImagePicker();
File? _imageFile;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppbar(),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: _getImage,
backgroundColor: Colors.blue,
child: Icon(Icons.add_a_photo),
),
);
}
Future<void> _getImage() async {
//ImagePiker
var image = await _picker.pickImage(source: ImageSource.gallery);
setState(() {
_imageFile = File(image!.path);
});
}
And this is my full code about this page. (Firebase code is included)
import 'dart:io';
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class CreatePage extends StatefulWidget {
//user info
const CreatePage({Key? key, required this.user}) : super(key: key);
final User user;
#override
_CreatePageState createState() => _CreatePageState();
}
class _CreatePageState extends State<CreatePage> {
//input text
final TextEditingController createText = TextEditingController();
//ImagePicker
final ImagePicker _picker = ImagePicker();
File? _imageFile;
//_createPageState가 제거될 때 호출됨
#override
void dispose() {
// TODO: implement dispose
createText.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppbar(),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: _getImage,
backgroundColor: Colors.blue,
child: Icon(Icons.add_a_photo),
),
);
}
_buildAppbar() {
return AppBar(
actions: [
IconButton(
icon: Icon(Icons.send),
onPressed: () {
_uploadPost(context);
},
),
],
);
}
_buildBody() {
return SingleChildScrollView(
child: Column(
children: [
_imageFile == null ? Text("No Image") : Image.file(_imageFile!),
TextField(
controller: createText,
decoration: InputDecoration(
hintText: "내용을 입력하세요",
),
)
],
),
);
}
//gallery image
Future<void> _getImage() async {
var image = await _picker.pickImage(source: ImageSource.gallery);
setState(() {
_imageFile = File(image!.path);
});
}
Future _uploadPost(BuildContext context) async {
final firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('post')
.child('${DateTime.now().microsecondsSinceEpoch}.png');
final task = await firebaseStorageRef.putFile(
_imageFile!, SettableMetadata(contentType: "image/png")
);
final uri = await task.ref.getDownloadURL();
//database document
final doc = FirebaseFirestore.instance.collection('post').doc();
//json type
await doc.set({
'id': doc.id,
'photoUrl': uri.toString(), //storage file url
'contents': createText, //user input text
'email': widget.user.email, //user email
'displayName': widget.user.displayName, //user name
'userPhotoUrl': widget.user.photoURL, //user profile image
});
//return page
Navigator.pop(context);
}
}
Pressing the floatingActionButton turns off the app and outputs the following error.
Lost connection to device.
May I know the cause of this?
Thank you in advance.

try adding dependency
image_picker: ^0.8.3+2
import 'package:image_picker/image_picker.dart';
then add this code
String url = "";
ImagePicker image = ImagePicker();
File ? file;
getImage() async {
var img = await image.pickImage(source: ImageSource.gallery);
setState(() {
file = File(img!.path);
});
}
And add:
onTap: () {
getImage();
},
add code:
child: file != null ?
Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
color: Colors.black,
margin: EdgeInsets.only(top: 80),
width: double.infinity,
height: 250,
child: Image.file(
file!,
fit: BoxFit.contain,
),
),
),

My guess is that you don't have permission to access the Media on the device, thus aborting the app the moment you try to do so. Check out the permission handler package.

Related

Why does my UI load the old image instead of the new one when I navigate to my route?

I am facing an issue with the state of my Flutter application.
A user can pick an image from their gallery using the Image Picker package from pub.dev. That goes smoothly, but I am then trying to save the picked image to local storage, with the help of the Path Provider package.
As demonstrated in this quick gif, you can see that picking an image indeed replaces the old one. However, when leaving the page and navigating back to it, the UI displays the old image instead of the new one.
Issue in this gif
Here is the code for the profile picture stateful widget:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'custom_profile_picture.dart';
import 'default_profile_picture.dart';
class ProfilePicture extends StatefulWidget {
const ProfilePicture({
Key? key,
}) : super(key: key);
#override
State<ProfilePicture> createState() => _ProfilePictureState();
}
class _ProfilePictureState extends State<ProfilePicture> {
final ImagePicker _picker = ImagePicker();
XFile? pickedFile;
File? localImage;
#override
void initState() {
super.initState();
loadImage();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
pickedFile != null
? CustomProfilePicture(image: File(pickedFile!.path))
: const DefaultProfilePicture(),
TextButton(
onPressed: pickImage,
child: const Text(
'Change picture',
style: TextStyle(fontSize: 12),
),
),
],
);
}
void pickImage() async {
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
if (image != null) {
print('New image picked');
setState(() {
pickedFile = image;
});
saveImage(image);
}
}
void saveImage(XFile img) async {
String path = (await getApplicationDocumentsDirectory()).path;
File convertedImg = File(img.path);
String fileName = "profilepicture";
File? localImage = await convertedImg.copy("$path/$fileName");
print("Image was saved under: $path/$fileName");
}
void loadImage() async {
String fileName = "profilepicture";
String path = (await getApplicationDocumentsDirectory()).path;
if (await File("$path/$fileName").exists()) {
print('The image exists. Loading image from:');
print('$path/$fileName');
setState(() {
pickedFile = XFile("$path/$fileName");
});
}
}
}
Here is the code for the Profile page, in which is located the profile picture component:
import 'package:flutter/material.dart';
import 'widgets/profile_picture.dart';
import 'widgets/custom_table.dart';
import 'widgets/about_me_content.dart';
import 'widgets/service_info_content.dart';
class ProfileView extends StatelessWidget {
const ProfileView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFe3e3e3),
appBar: AppBar(
foregroundColor: Colors.blue,
title: const Text(
'Profile view',
style: TextStyle(fontWeight: FontWeight.bold),
),
centerTitle: true,
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
),
body: SingleChildScrollView(
clipBehavior: Clip.none,
physics: const AlwaysScrollableScrollPhysics(),
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
child: Align(
alignment: Alignment.center,
child: Column(
children: [
const ProfilePicture(),
const Text(
'William Dupont',
style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
CustomTable(tableTitle: 'About me', content: AboutMeContent(),),
const SizedBox(height: 20),
CustomTable(tableTitle: 'My service info', content: ServiceInfoContent(),),
],
),
),
),
),
);
}
}
Any question, let me know.
I have found a fix to this issue.
I evict the image at the current path using the evict method.
Code:
void loadImage() async {
String fileName = "profilepicture";
String path = (await getApplicationDocumentsDirectory()).path;
if (await File("$path/$fileName").exists()) {
print('The image exists. Loading image from:');
print('$path/$fileName');
await FileImage(File('$path/$fileName)).evict();
setState(() {
pickedFile = XFile("$path/$fileName");
});
}
}

PickedImage getting null

I want to save an image locally on Device after Picking the Image From Gallery By using Path provider package . but _image file variable gets null after Selecting an Image From Gallery . Thats Why the Screen keeps Stuck on CircularProgressIndicator Screen . Can You Please Help me out of this null _image file variable.
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class SaveImage extends StatefulWidget {
const SaveImage({ Key? key }) : super(key: key);
#override
_SaveImageState createState() => _SaveImageState();
}
File? _image;
Future<File?> getImage() async{
var image = File(await ImagePicker.platform
.pickImage(source: ImageSource.gallery)
.then((value) => value.path));
final Directory directory = await getApplicationDocumentsDirectory();
final path=directory.toString();
final String fileName = basename(image.path);
// final String fileExtension = extension(image.path);
File newImage = await image.copy('$path/$fileName.jpg');
setState(() {
_image = newImage;
});
}
void setState(Null Function() param0) {
}
class _SaveImageState extends State<SaveImage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
Text('Pick Image From'),
SizedBox(height: 30,),
ElevatedButton(onPressed: (){
getImage();
}, child: Text('From Gallery')),
ElevatedButton(onPressed: (){
}, child: Text('From Camera')),
SizedBox(height: 50),
Container(
child: _image!=null?ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.file(
_image!,
fit: BoxFit.cover,
)):Center(child: CircularProgressIndicator(),)
),
],
),
),
),
);
}
}
Some things are wrong in your code:
The getImage() function is not inside your class, so the setState won't work.
You're not checking the return value of ImagePicker.platform.pickImage(), as it can be null. You have to check it before initialising a File with it.
directory.toString() does not return the path of the directory, but it returns "Directory: '/something'". It is meant to be printed. If you want the actual directory path, you need directory.path
If it's still not working, make sure you have done the right setup, as asked by image_picker (setting up your Info.plist for IOS...)
Here is your code, working as expected:
class SaveImage extends StatefulWidget {
const SaveImage({Key? key}) : super(key: key);
#override
_SaveImageState createState() => _SaveImageState();
}
class _SaveImageState extends State<SaveImage> {
File? _image;
Future<File?> getImage() async {
PickedFile? pickedFile =
await ImagePicker.platform.pickImage(source: ImageSource.gallery);
if (pickedFile == null) {
return null;
}
final File file = File(pickedFile.path);
final Directory directory = await getApplicationDocumentsDirectory();
final path = directory.path;
final String fileName = basename(pickedFile.path);
// final String fileExtension = extension(image.path);
File newImage = await file.copy('$path/$fileName');
setState(() {
_image = newImage;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
Text('Pick Image From'),
SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () {
getImage();
},
child: Text('From Gallery')),
ElevatedButton(onPressed: () {}, child: Text('From Camera')),
SizedBox(height: 50),
Container(
child: _image != null
? ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.file(
_image!,
fit: BoxFit.cover,
))
: Center(
child: CircularProgressIndicator(),
)),
],
),
),
),
);
}
}
If you want to store the image in the cache, you can use flutter_cache_manager library. It allows you to store and retrieve a file in cache.
Here is the code, updated to store the file in cache.
Notice that we use a key to identify our file in cache (I set it to the path of the file but you can set it to basically any String as long as it's unique to this file). If you want to use the file app-wide, you would probably need to store the key somewhere that can be accessed there.
class SaveImage extends StatefulWidget {
const SaveImage({Key? key}) : super(key: key);
#override
_SaveImageState createState() => _SaveImageState();
}
class _SaveImageState extends State<SaveImage> {
File? _image;
String? cachedFileKey;
Future<File?> getImage() async {
PickedFile? pickedFile =
await ImagePicker.platform.pickImage(source: ImageSource.gallery);
if (pickedFile == null) {
return null;
}
final File file = File(pickedFile.path);
final Uint8List fileBytes = await file.readAsBytes();
final cachedFile = await DefaultCacheManager()
.putFile(pickedFile.path, fileBytes, key: pickedFile.path);
setState(() {
cachedFileKey = pickedFile.path;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
Text('Pick Image From'),
SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () {
getImage();
},
child: Text('From Gallery')),
ElevatedButton(onPressed: () {}, child: Text('From Camera')),
const SizedBox(height: 50),
Container(
child: cachedFileKey != null
?
FutureBuilder<FileInfo?>(future: DefaultCacheManager().getFileFromCache(cachedFileKey!), builder: (context, snapShot) {
if (snapShot.hasData && snapShot.data != null) {
return ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.file(snapShot.data!.file,
fit: BoxFit.cover,
));
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
})
: const Center(
child: CircularProgressIndicator(),
)),
],
),
),
),
);
}
}
use image type PickedFile type. Ex:
PickedFile _image;
Future pickImageFromGallery(ImageSource source, BuildContext context) async {
var _image = await ImagePicker.platform.pickImage(source: source);
image = _image;
_uploadImage(image, context);
}
**for taking image path:
imageFile.path

error when using File with ImagePicker Flutter

The error is with this line: File selectedImage
I only have dart.io imported, not even dart.html so I'm not sure why I'm getting this error.
here is the longer piece of code
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:random_string/random_string.dart';
import 'package:tennis_event_app/services/crud.dart';
class CreateBlog extends StatefulWidget {
#override
_CreateBlogState createState() => _CreateBlogState();
}
class _CreateBlogState extends State<CreateBlog> {
late String pass, authorName, title, desc;
File selectedImage;
final picker = ImagePicker();
bool _isLoading = false;
CrudMethods crudMethods = new CrudMethods();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
selectedImage = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
(this is not the entire code but just a larger piece)
What exact error are you getting?
Suggestion
Please do well to put setState((){...}); in the if-statement like this:
if(pickedFile != null){
setState((){
selectedImage = File(pickedFile.path);
});
}else{
print('No image selected');
}
and Hot Reload.
SEE COMPLETE SOLUTION THAT WORKED FOR ME
class _ImageSelectorState extends State<ImageSelector> {
var imageFile;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 200.0,
height: 200.0,
color: Colors.grey.shade300,
child: imageFile != null
? Image.file(imageFile)
: Icon(
Icons.image,
),
),
SizedBox(height: 20.0),
//Button
Center(
child: ElevatedButton(
onPressed: _pickImage,
child: Text('Upload Image'),
),
),
],
),
);
}
_pickImage() async {
try {
final picker = await ImagePicker().getImage(
source: ImageSource.gallery,
);
if (picker != null) {
setState(() {
imageFile = File(picker.path);
});
}
} catch (e) {
print(e);
}
}
}
Result
Solution I Used:
I ended up changing File selectedImage; to File ? selectedImage;

How to test showDialog content in flutter?

is there a way to test the content within a show dialog?
I am trying to do BDD in the project, The following is the scenario:
As a User, I would like to add a photo or select one from the gallery so that I can use it on the item.
The following is the code I am using to test it but for some reason, the test fails.
add_item_view.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:my_app_mobile/models/graded_item/graded_item.dart';
import 'package:my_app_mobile/template/index.dart' as template;
import 'package:image_picker/image_picker.dart';
class AddItemView extends HookWidget {
final GradedItem gradedItem;
static final Key photoKey = Key('#photoKey');
static final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final void Function() onPhoto;
final ImagePicker _imagePicker = ImagePicker();
AddItemView({
#required this.gradedItem,
this.onPhoto,
});
#override
Widget build(BuildContext context) {
final _image = useState<File>();
Future getImage() async {
final pickedFile = await _imagePicker.getImage(source: ImageSource.camera);
if (pickedFile != null) {
_image.value = File(pickedFile.path);
} else {
print('No image selected.');
}
}
return Scaffold(
appBar: AppBar(),
body: SingleChildScrollView(
child: Form(
key: formKey,
child: Column(
children: [
GestureDetector(
onTap: () async {
if (onPhoto != null) {
onPhoto();
}
showDialog(
context: context,
barrierColor: Colors.red.withOpacity(.2),
builder: (context) {
return CameraOptions();
},
);
},
child: Container(
key: photoKey,
alignment: Alignment.center,
child: Icon(
Icons.add_a_photo,
color: Theme.of(context).primaryColor,
size: 44.0,
),
height: 100.0,
width: 100.0,
decoration: BoxDecoration(
color: template.colors.grey340,
borderRadius: BorderRadius.circular(10.0),
),
),
),
],
),
),
),
);
}
}
class CameraOptions extends StatelessWidget {
static final Key captureButtonPhotoKey = Key('#captureButtonPhotoKey');
static final Key chooseButtonPhotoKey = Key('#chooseButtonPhotoKey');
static final Key cancelButtonKey = Key('#cancelButtonKey');
final void Function() onCapture;
final void Function() onChoose;
final void Function() onCancel;
CameraOptions({this.onCapture, this.onChoose, this.onCancel});
#override
Widget build(BuildContext context) {
return Center(
child: Container(
height: 200.0,
width: 200.0,
child: Icon(Icons.camera, color: Colors.blue),
),
);
}
}
add_item_view_test.dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'my_app_mobile/models/graded_item/graded_item.dart';
import 'my_app_mobile/views/dashboard/children/collection/children/add_item/add_item.dart';
import 'package:mockito/mockito.dart';
void main() {
Widget mountApp({GradedItem gradedItem, void Function() onPhoto}) {
return MaterialApp(
home: AddItemView(
gradedItem: gradedItem,
onPhoto: onPhoto,
),
);
}
testWidgets('should build with no problems', (tester) async {
await tester.pumpWidget(mountApp(gradedItem: GradedItem.generate()));
expect(find.byType(AddItemView), findsOneWidget);
});
group('photo', () {
testWidgets(
'should photo widget be available',
(tester) async {
await tester.pumpWidget(mountApp(
gradedItem: GradedItem.generate(),
));
expect(find.byKey(AddItemView.photoKey), findsOneWidget);
},
);
testWidgets(
'should be able to call onPhoto handler when is available',
(tester) async {
final fn = MockedFunctions();
await tester.pumpWidget(mountApp(
gradedItem: GradedItem.generate(),
onPhoto: fn.onPhoto,
));
expect(find.byKey(AddItemView.photoKey), findsOneWidget);
await tester.tap(find.byKey(AddItemView.photoKey));
verify(fn.onPhoto()).called(1);
},
);
testWidgets(
'should onPhoto handler open camera options',
(tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Builder(
builder: (BuildContext context) {
return AddItemView(
gradedItem: GradedItem.generate(),
// onPhoto: fn.onPhoto,
);
},
),
),
),
);
await tester.tap(find.byKey(AddItemView.photoKey));
await tester.pumpAndSettle(const Duration(seconds: 1));
expect(find.byIcon(Icons.camera), findsOneWidget);
},
);
});
}
class MockedFunctions extends Mock {
void onPhoto();
}
Is there a way to do testing on a showDialog function?
Solved, for some reason, the code I posted is working, I restarted my computer and now they are working.

problem putting progressDialog.shide () in flutter

I am new to flutter and I am having the following problem.
I am trying to use the progressDialog in in a listview, I make the query to my database, I extract the list and pass it to the listview, I am trying to use the progressDialog so when I start loading the list it will run and tell the user to wait, and when I finish loading the list then the progressDialog is hidden, so far it works for me by bringing me the list and the progressDialog is executed saying to wait, but when I put the progressDialog.hide where the loading of the list ends I this is not accepting that line of code (progressDialog .hidde)
image:
enter image description here
import 'dart:convert';
import 'package:fluterproyecto1/Modulos/DetalleUser.dart';
import 'package:flutter/material.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
String username2 = '';
String profesion = '';
String name = '';
class MemberPage extends StatefulWidget {
MemberPage({Key key}) : super(key: key);
#override
_MemberPageState createState() => _MemberPageState();
}
class _MemberPageState extends State<MemberPage> {
Map data;
List userData;
ProgressDialog progressDialog;
String name = '';
Future getData() async {
http.Response response =
await http.get("http://masciudad.com.co/flutter/getdata.php");
data = json.decode(response.body);
//setState(() {
//progressDialog.show();
userData = data["data"];
//progressDialog.hide();
//});
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
progressDialog = ProgressDialog(context, type: ProgressDialogType.Normal);
progressDialog.style(message: 'Por favor espere...');
progressDialog.show();
setState(() {
obtenerPreferencias();
});
return Scaffold(
appBar: AppBar(
title: Text("Bienvenido $username2"),
),
body: ListView.builder(
itemCount: userData == null ? 0 : userData.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
children: <Widget>[
Image.asset(
"assets/128.jpg",
width: 30.0,
height: 30.0,
),
//CircleAvatar(
///cuando la imagen es de interntet
//backgroundImage: NetworkImage(
// "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"),
//),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
"${userData[index]["username"]} - ${userData[index]["profesion"]}",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w700,
),
),
)
],
),
),
onTap: () => Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new DetalleUser(name: userData[index]["username"]))),
);
},
),
//Navigator.of(context).push(MaterialPageRoute(
// builder: (BuildContext context) => MyHomePage()));
//Navigator.pushReplacementNamed(context, "/MyHomePage");
);
}
Future obtenerPreferencias() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
username2 = preferences.get("username2") ?? "";
profesion = preferences.get("profesion") ?? "";
});
}
Future destruirPreferencias() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.clear();
}
}
You can copy paste run full code below
You can use addPostFrameCallback and put logical in another function getRelatedData()
code snippet
void getRelatedData() async {
progressDialog = ProgressDialog(context, type: ProgressDialogType.Normal);
progressDialog.style(message: 'Por favor espere...');
progressDialog.show();
await getData();
await obtenerPreferencias();
progressDialog.hide();
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
getRelatedData();
});
}
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
String username2 = '';
String profesion = '';
String name = '';
class MemberPage extends StatefulWidget {
MemberPage({Key key}) : super(key: key);
#override
_MemberPageState createState() => _MemberPageState();
}
class _MemberPageState extends State<MemberPage> {
Map data;
List userData;
ProgressDialog progressDialog;
String name = '';
Future getData() async {
http.Response response =
await http.get("http://masciudad.com.co/flutter/getdata.php");
data = json.decode(response.body);
//setState(() {
//progressDialog.show();
userData = data["data"];
print("getData Done");
//progressDialog.hide();
//});
}
void getRelatedData() async {
progressDialog = ProgressDialog(context, type: ProgressDialogType.Normal);
progressDialog.style(message: 'Por favor espere...');
progressDialog.show();
await getData();
await obtenerPreferencias();
progressDialog.hide();
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
getRelatedData();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bienvenido $username2"),
),
body: ListView.builder(
itemCount: userData == null ? 0 : userData.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
children: <Widget>[
Image.network(
"https://picsum.photos/250?image=9",
width: 30.0,
height: 30.0,
),
//CircleAvatar(
///cuando la imagen es de interntet
//backgroundImage: NetworkImage(
// "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"),
//),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
"${userData[index]["username"]} - ${userData[index]["profesion"]}",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w700,
),
),
)
],
),
),
onTap: () {
/*Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new DetalleUser(name: userData[index]["username"])));*/
});
},
),
//Navigator.of(context).push(MaterialPageRoute(
// builder: (BuildContext context) => MyHomePage()));
//Navigator.pushReplacementNamed(context, "/MyHomePage");
);
}
Future obtenerPreferencias() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
username2 = preferences.get("username2") ?? "";
profesion = preferences.get("profesion") ?? "";
});
}
Future destruirPreferencias() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.clear();
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MemberPage(),
);
}
}
Dear #Yeimer I would suggest read documentation carefully
https://pub.dev/packages/progress_dialog
Add the Package this
dependencies:
progress_dialog: ^1.2.4
1
Initialize your ProgressDialog object
final ProgressDialog prDialog = ProgressDialog(context);
//For normal dialog
prDialog = ProgressDialog(context,type: ProgressDialogType.Normal, isDismissible: true/false, showLogs: true/false);
2 Showing the progress dialog
await pr.show();
3
Dismissing the progress dialog
prDialog.hide().then((isHidden) {
print(isHidden);
});
// or simply
await prDialog.hide();