Upload chosen image to the API in Flutter using image picker plugin - api

I want to upload the image into the API. I tried this code but I got an error
File not found
If I send an image file using Postman, it is working successfully. Here I attached the Postman screenshot, for upload the image I gave the image path and in addition for my document, I want to attach the user id please tell me a solution? thank you
This is my code
class _UserProfileEditState extends State<UserProfileEdit> {
// String imagepath='';
File _profileImage;
String base64Image;
DatabaseHelper databaseHelper = new DatabaseHelper();
int parentid;
_handleimagefromgallary() async {
File imagefile = await ImagePicker.pickImage(source: ImageSource.gallery);
if(imagefile!=null) {
setState(() {
_profileImage = imagefile;
});
}
}
_displayprofilephoto()
{
if(_profileImage==null)
{
if(widget.parentsInfo.data.photo==null)
{
return AssetImage('assets/images/parentimg.png');
}
else
{
return CachedNetworkImageProvider(widget.parentsInfo.data.photo);
}
}
else
{
return FileImage(_profileImage);
}
}
#override
Widget build(BuildContext context) {
parentid=widget.parentsInfo.data.id;
return Scaffold(
appBar: AppBar(
title: Center(
child: Text('Edit Profile'),
),
),
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height * 1.5,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Container(
height: 160.0,
width: 160.0, //MediaQuery.of(context).size.width,
child: new CircleAvatar(
radius: 50.0,
backgroundColor: Colors.green,
backgroundImage: _displayprofilephoto(),
),
),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(''),
InkWell(
child: Icon(Icons.add_photo_alternate),
onTap:_handleimagefromgallary,
),
],
),
),
showpdatebutton(),
This is the method to upload:
Future _updateprofilepicture() async{
// _profileImage=await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
// var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
// var path =await FlutterAbsolutePath.getAbsolutePath(_profileImage.absolute.path);
var path=await FlutterAbsolutePath.getAbsolutePath(_profileImage.path);
if(path==null)
{
}
else
{
// call controller
print(path);
String id=parentid.toString();
databaseHelper.parentprofileupdate(path, id);
// databaseHelper.parentprofileupdate(_profileImage, id);
}
}
Widget showpdatebutton() {
if(_profileImage!=null)
{
return OutlineButton(
child: Text('Update Profile Picture'),
onPressed: (){
_updateprofilepicture();
}
);
}
else
{
return Container();
}
}
}
My database helper class:
Future<ParentProfileUpdate> parentprofileupdate(String path,String id) async
{
Map mapValue;
var data;
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
String myUrl = "$serverUrl/api/v1/upload_parent_image";
await http.post(myUrl,
headers: {
// 'Accept':'application/json',
"HttpHeaders.contentTypeHeader": "application/json",
'Authorization' : 'Bearer $value'
},
body: {
"photo" :path,
"id":id,
}).then((response) {
status = response.body.contains('error');
mapValue=json.decode(response.body);
var data = json.decode(response.body);
print(data);
});
}

Related

Error fetching data from api and display it

I want to make a get request from my restApi and then display the data in a listView but for some reason it is not working.
The error I'm getting:
The getter 'length' was called on null.
Receiver: null
Tried calling: length
Api call (apiBaseHelper.dart)
Future<List<Post>> getAllPosts() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;
final getPublishedPostUrl = "http://192.168.1.7:5000/post/all";
final response = await http.get(getPublishedPostUrl, headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $value'
});
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((posts) => new Post.fromJson(posts)).toList();
} else {
throw "something ";
}
}
PostListView
class PostListView extends StatelessWidget {
final List<Post> posts;
PostListView({Key key, this.posts}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Container(
constraints: BoxConstraints.expand(
height:
Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0,
),
color: Colors.white10,
alignment: Alignment.center,
child: Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
contentPadding: EdgeInsets.all(10.0),
title: new Text(posts[index].title),
leading: new Image.network(
posts[index].picture,
fit: BoxFit.cover,
height: 40.0,
width: 40.0,
),
subtitle: Text(posts[index].category),
),
],
),
),
),
],
);
},
));
}
}
homePage.dart
class HomePage extends StatefulWidget {
final ApiBaseHelper apiBaseHelper = ApiBaseHelper();
#override
State<StatefulWidget> createState() {
return _HomePageState();
}
}
class _HomePageState extends State<HomePage> {
Future<List<Post>> futurePost;
#override
void initState() {
super.initState();
futurePost = ApiBaseHelper().getAllPosts();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.teal,
body: new Padding(
padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0),
child: FutureBuilder<List<Post>>(
future: ApiBaseHelper().getAllPosts(),
builder: (context, AsyncSnapshot<List<Post>> snapshot) {
if (snapshot.hasError) {
print(snapshot.error);
}
return snapshot.hasData
? PostListView()
: Center(child: CircularProgressIndicator());
},
),
),
);
}
}
I have been working on it for like 2 days and I don't know where the problem exactly
I'm sorry if it's too much code. thank you in advance
This code section here ,
return snapshot.hasData
? PostListView()
: Center(child: CircularProgressIndicator());
Add PostListView(posts:snapshot.data)
Tell me if it works.

returning null user back from function

I am working on Login page with Local db SQL in flutter.
The page isn't creating a SQL table and returning null user, thus showing the snackbar "wrong email".
I have tried to debug but can't find the solution as i am pretty new at this.
This is my sign up page:
class _RegisterState extends State<Register> {
DatabaseHelper db = new DatabaseHelper();
TextEditingController emailController = TextEditingController();
TextEditingController mobileController = TextEditingController();
Future<User> _loginUser(String email,String mobile) async{
User saveUser = User.fromMapObject({
email:"hfah#gmail.com",
mobile:"1432567890"
});
await db.saveUser(saveUser).then((val) async {
if(val == 1){
User user = await db.loginUser(email, mobile);
return user;
}
});
}
final _formKey = GlobalKey<FormState>();
final scaffoldKey = new GlobalKey<ScaffoldState>();
#override
Widget build(BuildContext context) {
final bgColor = const Color(0xFF4b0081);
return Scaffold(
resizeToAvoidBottomPadding: false,
backgroundColor: bgColor,
key: scaffoldKey,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image(
image: AssetImage("assets/newlogo2.png"),
width: 200,
height: 50,
),
Container(
padding: const EdgeInsets.only(top:20.0, right: 20, left: 20),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: "Mobile No",
labelStyle: TextStyle(color: Colors.white)
),
style: TextStyle(color: Colors.white, fontSize: 20.0),
onChanged: (val) {
setState(() => mob = val);
},
controller: emailController,
),
SizedBox(height: 20.0,),
TextFormField(
validator: (val) => val.isEmpty ? 'Enter an Email' : null,
decoration: InputDecoration(
labelText: "Email ID",
labelStyle: TextStyle(color: Colors.white)
),
style: TextStyle(color: Colors.white, fontSize: 20.0),
onChanged: (val){
setState(() => email = val);
},
controller: mobileController,
),
SizedBox(height: 20.0,),
RaisedButton(
color: Colors.white,
child: Text(
'Register',
style: TextStyle(color: bgColor),
),
onPressed: () async {
User user = await _loginUser(emailController.text, mobileController.text);
if(user != null){
Navigator.of(context).push(MaterialPageRoute<Null>(
builder: (BuildContext context){
return new Home(
user:user,
);
}
));
}else{
scaffoldKey.currentState.showSnackBar(
SnackBar(content: Text("Wrong email"),)
);
}
},
splashColor: Colors.grey,
),
SizedBox(height: 12.0,),
Text(
error,
style: TextStyle(
color: Colors.red,
fontSize: 14.0
),
),
FlatButton(
color: bgColor,
child: Text(
'Back to Sign In',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
onPressed: () async {
setState(() {
//widget.toggleView();
},);
},
),
],
),
),
),
],
),
);
}
This is DatabaseHelper class
class DatabaseHelper{
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
String colemail = 'emial_id';
String tablename = 'User';
String colMobile = 'mobild_no';
Future<Database> get db async{
if(_db != null) return _db;
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async{
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "main.db");
var theDb = await openDatabase(path,version:1,onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db,int version) async{
await db.execute("""
CREATE TABLE User(
user_id INTEGER PRIMARY KEY,
email_id TEXT,
mobile_no TEXT
)""");
print("Table created");
}
Future<int> saveUser(User user) async{
var dbClient = await db;
int res = await dbClient.insert(tablename, user.toMap());
return res;
}
Future<User> loginUser(String email,String mobile) async{
var dbClient = await db;
String sql = "SELECT * FROM User WHERE email_id = '$email' AND
mobile_no = '$mobile' ";
var result = await dbClient.rawQuery(sql);
if(result.length == 0) return null;
return User.fromMapObject(result.first);
}
}
And this is User class
class User{
int _user_id;
String email_id;
String mobile_no;
User(this.email_id,this.mobile_no,this._user_id);
String get emailID => email_id;
String get mobileNO => mobile_no;
int get user_id =>_user_id;
set emailID(String newMail){
this.email_id = newMail;
}
set mobileNO(String newMob){
this.mobile_no = newMob;
}
Map <String,dynamic> toMap(){
return {
'email_id': email_id,
'mobile_no': mobile_no,
'user_id':_user_id
};
}
User.fromMapObject(dynamic map){
this.email_id = map['email_id'];
this.mobile_no = map['mobile_no'];
this._user_id = map['user_id'];
}
}
Please help !!!
In _RegisterState class, I don't see if you instantiated DatabaseHelper db; so db is null and you are trying to invoke saveUser on null instance variable in following code
await db.saveUser(saveUser).then((val) async {
if(val == 1){
User user = await db.loginUser(email, mobile);
return user;
}
});
Replace this
Scaffold.of(context).showSnackBar(SnackBar(content: Text("Wrong email"),));
with
scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Wrong email")));
You just need to instantiate db:
class _RegisterState extends State<Register> {
DatabaseHelper db = new DatabaseHelper();
....
}
For the Snackbar error, replace this code:
else{
Scaffold.of(context).showSnackBar(
SnackBar(content: Text("Wrong email"),)
);
}
with:
else{
globalKey.currentState.showSnackBar(
SnackBar(content: Text("Wrong email"),)
);
}

How do I deal with logins on different devices based on API response in flutter?

I'm confused about how to deal with multiple logins with different devices, and I want to give the function back to the login layout when there are other devices that have just logged in to the same user
Future<EventArticleList> getEventArticleList(String token) async {
BuildContext context;
Map<String, String> headers = {
"Accept": "application/json",
"Authorization": "Bearer $token"
};
var response = await client.get('$endpoint/', headers: headers);
if (response.statusCode == 200) {
print("Masuk Data");
return EventArticleList.fromJson(
json.decode(response.body),
);
} else if (response.statusCode == 401) {
print("401");
return Navigator.of(context)
.pushNamedAndRemoveUntil(RoutePaths.Login, (_) => false);
} else {
throw Exception("ini Eror apa ?");
}
}
the compilation appears I try to add the navigator back to status.code == 401
NoSuchMethodError: The method 'ancestorStateOfType' was called on null
Try this code
Your main class
import 'package:flutter/material.dart';
import 'package:flutterapitut/view/adddata.dart';
import 'package:flutterapitut/view/dashboard.dart';
import 'package:flutterapitut/view/login.dart';
import 'package:flutterapitut/view/register.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final String title='';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter CRUD API',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginPage(title: 'Flutter CRUD API'),
routes: <String,WidgetBuilder>{
'/dashboard' : (BuildContext context) => new Dashboard(title:title),
'/login' : (BuildContext context) => new LoginPage(title:title),
},
);
}
}
Your Database Helper class
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class DatabaseHelper{
String serverUrl = "http://flutterapitutorial.codeforiraq.org/api";
var status ;
var token ;
loginData(String email , String password) async{
String myUrl = "$serverUrl/login1";
final response = await http.post(myUrl,
headers: {
'Accept':'application/json'
},
body: {
"email": "$email",
"password" : "$password"
} ) ;
status = response.body.contains('error');
var data = json.decode(response.body);
if(status){
print('data : ${data["error"]}');
}else{
print('data : ${data["token"]}');
_save(data["token"]);
}
}
_save(String token) async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = token;
prefs.setString(key, value);
}
read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
print('read : $value');
}
}
Your login class
import 'package:flutter/material.dart';
import 'package:flutterapitut/Controllers/databasehelper.dart';
import 'package:flutterapitut/view/dashboard.dart';
import 'package:flutterapitut/view/register.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginPage extends StatefulWidget{
LoginPage({Key key , this.title}) : super(key : key);
final String title;
#override
LoginPageState createState() => LoginPageState();
}
class LoginPageState extends State<LoginPage> {
read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
if(value != '0'){
Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context) => new Dashboard(),
)
);
}
}
#override
initState(){
read();
}
DatabaseHelper databaseHelper = new DatabaseHelper();
String msgStatus = '';
final TextEditingController _emailController = new TextEditingController();
final TextEditingController _passwordController = new TextEditingController();
_onPressed(){
setState(() {
if(_emailController.text.trim().toLowerCase().isNotEmpty &&
_passwordController.text.trim().isNotEmpty ){
databaseHelper.loginData(_emailController.text.trim().toLowerCase(),
_passwordController.text.trim()).whenComplete((){
if(databaseHelper.status){
_showDialog();
msgStatus = 'Check email or password';
}else{
Navigator.pushReplacementNamed(context, '/dashboard');
}
});
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Login',
home: Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Container(
child: ListView(
padding: const EdgeInsets.only(top: 62,left: 12.0,right: 12.0,bottom: 12.0),
children: <Widget>[
Container(
height: 50,
child: new TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email',
hintText: 'Place your email',
icon: new Icon(Icons.email),
),
),
),
Container(
height: 50,
child: new TextField(
controller: _passwordController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Password',
hintText: 'Place your password',
icon: new Icon(Icons.vpn_key),
),
),
),
new Padding(padding: new EdgeInsets.only(top: 44.0),),
Container(
height: 50,
child: new RaisedButton(
onPressed: _onPressed,
color: Colors.blue,
child: new Text(
'Login',
style: new TextStyle(
color: Colors.white,
backgroundColor: Colors.blue),),
),
),
new Padding(padding: new EdgeInsets.only(top: 44.0),),
Container(
height: 50,
child: new Text(
'$msgStatus',
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold),
),
),
new Padding(padding: new EdgeInsets.only(top: 44.0),),
Container(
height: 50,
child: new FlatButton(
onPressed: ()=>Navigator.of(context).push(
new MaterialPageRoute(
builder: (BuildContext context) => new RegisterPage(),
)
)
,
color: Colors.blue,
child: new Text(
'Register',
style: new TextStyle(
color: Colors.white,
),),
),
),
],
),
),
),
);
}
void _showDialog(){
showDialog(
context:context ,
builder:(BuildContext context){
return AlertDialog(
title: new Text('Failed'),
content: new Text('Check your email or password'),
actions: <Widget>[
new RaisedButton(
child: new Text(
'Close',
),
onPressed: (){
Navigator.of(context).pop();
},
),
],
);
}
);
}
}
Here Dashboard is the class you expected to navigate after successfully login
Want more code visite here I hope this work correctly

In Flutter How to get image path after selecting images using Multi Image Picker?

I want to get an image path from selected multiple images, I'm using this link to select multiple images but I got assets, I want paths from selected multiple images because I want to upload into the API.
I added this dependency in pubspec.yaml If there any good way to do this, please tell me
multi_image_picker: ^4.6.3
This is my file upload class, This UI looks similar to Facebook.
import 'dart:typed_data';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
class UpdateStatus extends StatefulWidget {
#override
_UpdateStatusState createState() => _UpdateStatusState();
}
class _UpdateStatusState extends State<UpdateStatus> {
List<Asset> images = List<Asset>();
String _error = 'No Error Dectected';
Future<ByteData> byteData;
// List<int> imageData = byteData.buffer.asUint8List();
#override
void initState() {
// TODO: implement initState
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Create Post'),
actions: <Widget>[
Padding(
padding: const EdgeInsets.all(18.0),
child: InkWell(child: Text('POST',style: TextStyle(fontSize: 18.0),),onTap: ()
{
print('Post this post');
},),
)
],
),
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
width:MediaQuery.of(context).size.width ,
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
height: 300.0,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
keyboardType: TextInputType.multiline,
maxLines: 100,
style: new TextStyle(
fontSize: 18.0,
color: Colors.black
),
decoration: InputDecoration(
hintText: 'Enter your Post Details Here !',
border: InputBorder.none,
),
),
),
),
Divider(
thickness: 1.0,
),
Column(
children: <Widget>[
Container(
height: 40.0,
color: Colors.white70,
child: Padding(
padding:EdgeInsets.only(left: 18.0,),
child: InkWell(
child: Row(
children: <Widget>[
Icon(Icons.add_a_photo,),
Text(" Choose Image",style: TextStyle(fontSize: 24.0,),),
],
),
onTap: ()
{
print(images.toList().toString());
print('choose image from local');
},
),
),
),
Divider(
thickness: 1.0,
),
Container(
height: 40.0,
color: Colors.white70,
child: Padding(
padding:EdgeInsets.only(left: 18.0,),
child: InkWell(
child: Row(
children: <Widget>[
Icon(Icons.add_photo_alternate,),
Text(" Choose Video",style: TextStyle(fontSize: 24.0,),),
],
),
onTap: ()
{
print('choose video from local');
},
),
),
),
],
),
Divider(
thickness: 1.0,
),
Container(
height: 200,
child: Column(
children: <Widget>[
Center(child: Text('Error: $_error')),
RaisedButton(
child: Text("Pick images"),
onPressed: loadAssets,
),
Expanded(
child: buildGridView(),
)
],
),
),
/*
Column(
children: <Widget>[
Center(child: Text('Error: $_error')),
RaisedButton(
child: Text("Pick images"),
onPressed: loadAssets,
),
Expanded(
child: buildGridView(),
)
],
),
*/
],
),
),
),
);
}
Future<void> loadAssets() async {
List<Asset> resultList = List<Asset>();
String error = 'No Error Dectected';
ByteData byteData;
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 300,
enableCamera: true,
selectedAssets: images,
cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: MaterialOptions(
actionBarColor: "#abcdef",
actionBarTitle: "Ilma",
allViewTitle: "All Photos",
useDetailsView: false,
selectCircleStrokeColor: "#000000",
),
);
} on Exception catch (e) {
error = e.toString();
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
images = resultList;
_error = error;
print('000000000000000000000');
print('000000000000000000000');
print(images);
print('000000000000000000000');
print('000000000000000000000');
});
}
Widget buildGridView() {
return GridView.count(
crossAxisCount: 3,
children: List.generate(images.length, (index) {
Asset asset = images[index];
byteData=asset.getByteData();
print('0000');
print(byteData);
print('0000');
return AssetThumb(
asset: asset,
width: 300,
height: 300,
);
}),
);
}
}
Padding(
padding: const EdgeInsets.all(18.0),
child: InkWell(
child: Text(
'POST',
style: TextStyle(fontSize: 18.0),
),
onTap: () async {
List<MultipartFile> multipart = List<MultipartFile>();
for (int i = 0; i < images.length; i++) {
var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
}
},
),
)
I'm Using below Code to select multiple images by using file_picker: ^2.0.7 Library.
Long press to select multiple image. Once Image Selected you can use f arr to display the images.
List<File> f = List();
RaisedButton(
child: Text("Pick Image"),
onPressed: () async {
FilePickerResult result = await FilePicker.platform.pickFiles(
allowMultiple: true,
type: FileType.custom,
allowedExtensions: ['jpg', 'png', 'jpeg'],
);
if (result != null) {
f = result.paths.map((path) => File(path)).toList();
setState(() {});
print(f);
}
},
),
Sample API Call For image upload and normal data. Image uploaded column should be arr ( photo[] ).
List<MultipartFile> newList = new List<MultipartFile>();
Future<String> ImageUpload() async {
var request = http.MultipartRequest('POST', url);
request.headers["Authorization"] = pref.getString("token");
request.headers["Accept"] = "application/json";
//Image Data
for (int i = 0; i < f.length; i++) {
newList.add(await http.MultipartFile.fromPath('photo[]', f[i].path));
}
request.files.addAll(newList);
Map<String, dynamic> data = Map<String, String>();
//normal data
data["user_id"] = user_id;
data["project_id"] = pro_id;
request.fields.addAll(data);
var res = await request.send();
if (res.statusCode == 200) {
debugPrint("Status${res}");
}else {
debugPrint("status code${res}");
}
}
Try This You can select and upload multiple images easily. Thank you.
Use multi_image_picker 4.7.14 library to pick Multiple Images. use below code you can send selected asset image as a file. `
//Inside Widget Builder
FlatButton(
child: Image.asset(
"assets/images/camera.png",
color: Colors.grey,
),
onPressed: loadAssets,
),
SizedBox(
// height: SizeConfig.safeBlockHorizontal * 10,
height: MediaQuery.of(context).size.height / 2,
child: Column(
children: <Widget>[
Expanded(
child: buildGridView(),
),
],
),
)
List<File> fileImageArray = [];
List<String> f = List();
List<Asset> resultList = List<Asset>();
List<Asset> images = List<Asset>();
Future<void> loadAssets() async {
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 4,
enableCamera: true,
selectedAssets: images,
cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: MaterialOptions(
actionBarColor: "#abcdef",
actionBarTitle: "Example App",
allViewTitle: "All Photos",
useDetailsView: false,
selectCircleStrokeColor: "#000000",
),
);
} on Exception catch (e) {
error = e.toString();
}
if (!mounted) return;
for (int i = 0; i < resultList.length; i++) {
var path =
await FlutterAbsolutePath.getAbsolutePath(resultList[i].identifier);
print(path);
f.add(File(path));
}
setState(() {
images = resultList;
});
// return fileImageArray;
}
//image PreView
Widget buildGridView() {
return GridView.count(
crossAxisCount: 4,
children: List.generate(images.length, (index) {
Asset asset = images[index];
return AssetThumb(
asset: asset,
width: 50,
height: 50,
);
}),
);
}
API Call : while image uploading place use multipart file
List<MultipartFile> newList = new List<MultipartFile>();
Future<String> multiImagePostAPI() async {
var request = http.MultipartRequest('POST', url);
request.headers["Authorization"] = pref.getString("token");
request.headers["Accept"] = "application/json";
for (int i = 0; i < f.length; i++) {
newList.add(await http.MultipartFile.fromPath('photo[]', f[i].path));
}
request.files.addAll(newList);
Map<String, dynamic> data = Map<String, String>();
data["user_id"] = user_id;
data["project_id"] = pro_id;
data["title"] = titleController.text;
request.fields.addAll(data);
var res = await request.send();
if (res.statusCode == 200) {
debugPrint("Status$res");
}else {
debugPrint("status : $res");
}
}
You can also select multiple images using file_picker: ^1.5.0+2 library and easy to get path of selected images
Future<int> getFilePath() async {
try {
files = await FilePicker.getMultiFile();
if (files == '') {
return 0;
}
else
{
setState(() {
this._filePath = files;
return 1;
});
}
} on PlatformException catch (e) {
print("Error while picking the file: " + e.toString());
}
}
show selected images by using ListView Builder like this
ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _filePath.length,
itemBuilder: (context,c)
{
return Card(
child: Image.file(_filePath[c],
fit: BoxFit.fill,
width: 400,
height: 400,
),
);
}
),

come from back navigation app not refreshing in flutter

When i am on edit profile screen i changed my details and back from the back icon, On the next screen my updated data not reflecting.
This is my home screen where i need to call below API:
Main.dart
#override
Widget build(BuildContext context) {
return new MaterialApp(
showPerformanceOverlay: false,
debugShowCheckedModeBanner: false,
title: 'hempmeASAP',
home: (is_loggedin) ? Home():Login(),
routes: {
"/home": (_) => new Home(),
"/login": (_) => new Login(),
"/signup": (_) => new Signup(),
"/forgot": (_) => new ForgotPassword()
},
);
}
home.dart
void initState() {
super.initState();
getProfileData();
}
getProfileData() {
customFun.readToken().then((val) {
setState(() {
access_token = val;
});
try{
(() async {
await restApis.getProfile(access_token).then((val) => setState((){
print(val);
name = (val["data"]["name"]).toString();
profile_img = val["data"]["avatarUrl"];
}));
})();
}catch(e){
setState(() {
showProgressBar = false;
//show_error = true;
//error_msg = "The exception thrown is $e";
});
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text("The exception thrown is $e"),
));
}
});
}
// I need to pass updated name and profile_img here
child: new Scaffold(
key: scaffoldKey,
//drawer: new Drawer(child: DrawerList()),
appBar: AppBarComponent(context: context, appbarTitle:appBarTitle, name: name, profile_img: profile_img),
)
app_bar_component.dart
class AppBarComponent extends AppBar {
AppBarComponent({Key key, BuildContext context, appbarTitle, name, profile_img, screenName})
: super(
key: key,
backgroundColor: Colors.white,
//centerTitle: false,
iconTheme: IconThemeData(
color: Color(0xff888888), //change your color here
),
title: Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Stack(
children: <Widget>[
CircleAvatar(
radius: 26.0,
backgroundImage: (profile_img != null && profile_img != "") ? NetworkImage("$profile_img"):NetworkImage('https://via.placeholder.com/150',scale: 1.0),
backgroundColor: Colors.transparent,
),
]
),
Padding(
padding: const EdgeInsets.all(10.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
margin: EdgeInsets.only(bottom: 2.0),
child: Text("$name",style: TextStyle(color: Color(0xff444444),fontSize: 16.0))
),
screenName != 'edit' ?
GestureDetector(
child: Text("Edit Profile", style: TextStyle(fontSize: 11.0, color: Colors.blue,decoration: TextDecoration.underline)),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Editprofile())
);
}
):Container()
]
)
)
],
),
),
actions: <Widget>[
new IconButton(
onPressed: () =>
customFun.logout().then((_) =>
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=> Login(logout:true)))
),
icon: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 8.0,top: 4.0),
child: Icon(Icons.exit_to_app,color: Color(0xff888888)),
),
]
)
),
],
);
}
editprofile.dart
void _submitlogin() {
final form = formKey.currentState;
Map _data;
if(form.validate()){
if(_newpassword != _confirmpassword){
setState(() {
show_error = true;
error_msg = "Confirm Password should match password";
});
}
showProgressBar = true;
customFun.readToken().then((val) {
access_token = val;
try{
(() async {
await restApis.postUpdateProfile(access_token,_name,_mobile,_oldpassword,_newpassword,_confirmpassword).then((val) => setState(() {
// print("response");
print(val);
if(val["success"]){
form.save();
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.green,
content: Text(val["message"]),
));
setState(() {
showProgressBar = false;
show_error = false;
});
_getProfleDetail();
}else{
showProgressBar = false;
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text(val["message"]),
));
}
}));
})();
}catch(e){
setState(() {
showProgressBar = false;
//show_error = true;
//error_msg = "The exception thrown is $e";
});
scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text("The exception thrown is $e"),
));
}
});
}
}
THESE ARE THE MAIN FUNCTIONS AND WHEN I UPDATE MY PROFILE AND BACK FROM NAVIGATION BACK ICON ON EDIT PROFILE SCREEN ON MY HOME PAGE APP BAR PROFILE PHOTO AND THE NAME IS NOT UPDATING. NAME AND PROFILE PHOTO SHOULD BE UPDATED IN APP.
I need to call getProfileData(); function when i am coming to home screen from edit profile screen.
UPDATED: My issue is when i update my image from updateprofile screen this result is not reflecting on the home screen.
Please let me know if any solution.