Home > Net >  How to pass image picker file from one page to another in flutter dart?
How to pass image picker file from one page to another in flutter dart?

Time:08-02

I'm trying to select image either from gallery or camera using imagepicker plugin and pass this image to another page and make post request using this passed image as I'm very beginner to flutter I'm not able to achieve this idea, my implementation is as below I referred this [solution][1] to implement this

First page

import 'dart:io';
import 'package:bg_remover_app/uploadBgImage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'uploadBgImage.dart';

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
  /// Variables
  File? imageFile;
  XFile? PFile;

  /// Widget
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Image Picker"),
        ),
        body: Container(
            child: imageFile == null
                ? Container(
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RaisedButton(
                    color: Colors.greenAccent,
                    onPressed: () {
                      _getFromGallery();
                    },
                    child: Text("PICK FROM GALLERY"),
                  ),
                  Container(
                    height: 40.0,
                  ),
                  RaisedButton(
                    color: Colors.lightGreenAccent,
                    onPressed: () {
                      _getFromCamera();
                    },
                    child: Text("PICK FROM CAMERA"),
                  )
                ],
              ),
            ): Container(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
               Image.file(
                imageFile!,
                fit: BoxFit.cover,
              ),
              RaisedButton(
                    color: Colors.greenAccent,
                    onPressed: (){Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => MyPage1(image:PFile)),
  );},  
                    child: Text("Choose Background Image"),
                  ),
                  // Container(
                  //   height: 40.0,
                  // ),
              ]
              )
              ,
              
            ),
            ),
            );
  }

  /// Get from gallery
  _getFromGallery() async {
    // ignore: deprecated_member_use
    final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.gallery,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
        PFile  = pickedFile;
      });
    }
  }

  /// Get from Camera
  _getFromCamera() async {
    final XFile? pickedFile = await ImagePicker().pickImage(
      source: ImageSource.camera,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
        PFile  = pickedFile;
      });
    }
  }
}

here I'm using image picker plugin and storing selected image property to pass it to next page using navigator push and my second page codes are as below

second page

import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;

class MyPage1  extends StatefulWidget {
 const MyPage1({Key?key,required this.image,}):super(key:key);
  /// Variables
  final XFile image;
  @override
  _MyPage1State createState() => _MyPage1State(image: null);
}

class _MyPage1State extends State<MyPage1> {
   File? imagefile1;
  const _MyPage1State({Key?key,required this.image,}):super(key:key);
  /// Variables
  final XFile image;
  File? imageFile;
  String? message  = "";
  uploadImage() async {
    final request = http.MultipartRequest(
      "POST", Uri.parse('https://flask_server.com/upload'));
    final headers = {"Content-type":"multipart/form-data"};
    request.files.add(http.MultipartFile('image1',
    imagefile1!.readAsBytes().asStream(),imagefile1!.lengthSync(),
    filename: imagefile1!.path.split("/").last));
    request.files.add(http.MultipartFile('image2',
    imageFile!.readAsBytes().asStream(),imageFile!.lengthSync(),
    filename: imageFile!.path.split("/").last));
    request.headers.addAll(headers);
    final response = await request.send();
    http.Response res = await http.Response.fromStream(response);
    final resJson = jsonDecode(res.body);
    message = resJson['message'];
    print(message);
    setState(() {
      
    });

    
  }
  /// Widget
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Image Picker"),
        ),
        body: Container(
            child: imageFile == null
                ? Container(
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RaisedButton(
                    color: Colors.greenAccent,
                    onPressed: () {
                      _getFromGallery();
                    },
                    child: Text("PICK FROM GALLERY"),
                  ),
                  Container(
                    height: 40.0,
                  ),
                  RaisedButton(
                    color: Colors.lightGreenAccent,
                    onPressed: () {
                      _getFromCamera();
                    },
                    child: Text("PICK FROM CAMERA"),
                  )
                ],
              ),
            ): Container(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
               Image.file(
                imageFile!,
                fit: BoxFit.cover,
              ),
              RaisedButton(
                    color: Colors.greenAccent,
                    onPressed: (){
  print('clicked!!');
  uploadImage();
  },  
                    child: Text("Change Background"),
                  ),
                  // Container(
                  //   height: 40.0,
                  // ),
              ]
              )
              ,
              
            ),
            ),
            );
  }

  /// Get from gallery
  _getFromGallery() async {
    // ignore: deprecated_member_use
    PickedFile? pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
      });
    }
  }

  /// Get from Camera
  _getFromCamera() async {
    PickedFile? pickedFile = await ImagePicker().getImage(
      source: ImageSource.camera,
      maxWidth: 1800,
      maxHeight: 1800,
    );
    if (pickedFile != null) {
      setState(() {
        imageFile = File(pickedFile.path);
      });
    }
  }
}

in second page im selecting image and collecting image from previous page with these two images i'm trying to make https post request with selected images but I'm not able to fetch image properly from previous page

How can I send images from first page to second page and with this make a http request? Any suggestions how to implement this properly and external guides links will be very helpful and highly appreciated
[1]: Passing image from one screen to another - Flutter

CodePudding user response:

You are already sending the XFile to you second screen in the constructor, what you can do is to access to it doing widget.image from the state.

You can do something like this:

Future<String> uploadImage(XFile image) async {
    File file = File(image.path);
    String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(file.path, filename: fileName),
    });
    response = await dio.post("/upload", data: formData);
    return response.data['message'];
}

This was done using Dio

After that just call uploadImage(widget.image) and should work fine.

CodePudding user response:

Hey the issue is you are not able to fetch the data that you have passed from the first screen so to get the data passed from screen 1 use widget.image for more refer to this answer Passing data between screens in Flutter

  • Related