Home > Software design >  The method 'readAsBytesSync' isn't defined for the type 'XFile'. Try correc
The method 'readAsBytesSync' isn't defined for the type 'XFile'. Try correc

Time:10-26

When I upgrade image_picker to image_picker: ^0.8.3 2 then I get some error as below : The method 'readAsBytesSync' isn't defined for the type 'XFile'. Try correcting the name to the name of an existing method, or defining a method named 'readAsBytesSync'.

in code

Img.Image image = Img.decodeImage(pickedImage.readAsBytesSync());

Please help to resolve this problem.

Thank you for your help.

full my code are :

    import 'dart:io';
    import 'package:flutter/material.dart';
    import 'package:flutter_vector_icons/flutter_vector_icons.dart';
    import 'package:image_picker/image_picker.dart';
    import 'package:http/http.dart' as http;
    import 'package:image/image.dart' as Img;
    import 'dart:math' as Math;
    import 'package:path_provider/path_provider.dart';
    import 'package:path/path.dart';
    import 'package:image_picker/image_picker.dart';
    import 'package:path_provider/path_provider.dart';
    import 'package:async/async.dart';

    class ProfileScreen extends StatefulWidget {
      @override
      _ProfileScreenState createState() => _ProfileScreenState();
    }

    class _ProfileScreenState extends State<ProfileScreen> {
      XFile pickedImage;
      ImagePicker _imagePicker = ImagePicker();
      File _imageUpload;
      String fileName;

      @override
      Widget build(BuildContext context) {
        double width = MediaQuery.of(context).size.width;
        double height = MediaQuery.of(context).size.height;
        return Stack(
          fit: StackFit.expand,
          children: [
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Color.fromRGBO(4, 9, 35, 1),
                    Color.fromRGBO(39, 105, 171, 1),
                  ],
                  begin: FractionalOffset.bottomCenter,
                  end: FractionalOffset.topCenter,
                ),
              ),
            ),
            Scaffold(
              backgroundColor: Colors.transparent,
              body: SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16,         vertical: 40),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Icon(
                            AntDesign.arrowleft,
                            color: Colors.white,
                          ),
                          Icon(
                            AntDesign.logout,
                            color: Colors.white,
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'My Profile',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 30,
                          fontFamily: 'Nisebuschgardens',
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                        height: height * 0.43,
                        child: LayoutBuilder(
                          builder: (context, constraints) {
                            double innerHeight = constraints.maxHeight;
                            double innerWidth = constraints.maxWidth;
                            return Stack(
                              fit: StackFit.expand,
                              children: [
                                Positioned(
                                  bottom: 0,
                                  left: 0,
                                  right: 0,
                                  child: Container(
                                    height: innerHeight * 0.72,
                                    width: innerWidth,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(30),
                                      color: Colors.white,
                                    ),
                                    child: Column(
                                      children: [
                                        SizedBox(
                                          height: 85,
                                        ),
                                        Text(
                                          'I Nyoman Gunartha',
                                          style: TextStyle(
                                            color: Color.fromRGBO(39, 105,        171, 1),
                                            fontFamily: 'Nunito',
                                            fontSize: 25,
                                          ),
                                        ),
                                        Text(
                                          'NoPeg : 210026',
                                          style: TextStyle(
                                            color: Color.fromRGBO(39, 105,        171, 1),
                                            fontFamily: 'Nunito',
                                            fontSize: 20,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                Positioned(
                                  top: 110,
                                  right: 20,
                                  child: Icon(
                                    AntDesign.setting,
                                    color: Colors.grey[700],
                                    size: 30,
                                  ),
                                ),
                                Positioned(
                                  top: 0,
                                  left: 0,
                                  right: 0,
                                  child: Center(
                                    child: Container(
                                      width: 150,
                                      height: 150,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular       (100.0),
                                        
                                      ),
                                      child: pickedImage != null
                                          ? Container(
                                              height: 200,
                                              width: 200,
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(100.0),
                                                image: DecorationImage(
                                                  image: FileImage(
                                                      File(pickedImage.path)),
                                                  fit: BoxFit.cover,
                                                ),
                                              ),
                                            )
                                          : Text('no image'),
                                    ),
                                  ),
                                ),
                              ],
                            );
                          },
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Container(
                        height: height * 0.3,
                        width: width,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(30),
                          color: Colors.white,
                        ),
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 15),
                          child: Column(
                            children: [
                              SizedBox(
                                height: 20,
                              ),
                              Text(
                                'Change Profile',
                                style: TextStyle(
                                  color: Color.fromRGBO(39, 105, 171, 1),
                                  fontSize: 20,
                                  fontFamily: 'Nunito',
                                ),
                              ),
                              Divider(
                                thickness: 2.5,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  ElevatedButton(
                                      child: Text('Select Image'),
                                      onPressed: () {
                                        _selectImage();
                                      }),
                                  SizedBox(
                                    width: 25,
                                  ),
                                  ElevatedButton(
                                      child: Text('Upload'),
                                      onPressed: () {
                                        upload(imageFile: pickedImage);
                                      }),
                                ],
                              ),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            )
          ],
        );
      }

      void _selectImage() async {
        try {
          final checkDataImage =
              // await _imagePicker.pickImage(source: ImageSource.gallery);
              await _imagePicker.pickImage(source: ImageSource.camera);

          if (checkDataImage != null) {
            print(checkDataImage.name);
            print(checkDataImage.path);
            setState(() {
              pickedImage = checkDataImage;
            });
          }
        } catch (err) {
          print(err);
          pickedImage = null;
        }

        final tempDir = await getTemporaryDirectory();
        final path = tempDir.path;

        Img.Image image = Img.decodeImage(pickedImage.readAsBytesSync());
        // Img.Image image = Img.decodeImage(pickedImage.readAsBytes());
        Img.Image smallerImg = Img.copyResize(image, width: 500);

        int rand = new Math.Random().nextInt(999999999);

        var compressImg = new File('$path/image_$rand.jpg')
          ..writeAsBytesSync(Img.encodeJpg(smallerImg, quality: 90));

        setState(() {
          if (!mounted) return;
          _imageUpload = compressImg;
        });
      }

      upload({File imageFile}) async {
        // var stream = new http.ByteStream(imageFile.openRead());
        // stream.cast();
        var stream = http.ByteStream(imageFile.openRead())..cast();
        var length = await imageFile.length();
        var multipartFile = http.MultipartFile('image', stream, length,
            filename: basename(imageFile.path));

        var uri = Uri.parse(urlAPI   "upload-image.php");

        var request = new http.MultipartRequest("POST", uri);

        request.files.add(multipartFile);

        try {
          var response = await request.send();

          if (response.statusCode == 200) {
            var responseString = await response.stream.bytesToString();
            print(responseString);
          }
        } catch (e) {
          print('Network issue: '   e.toString());
        }
      }
    }





    

CodePudding user response:

You should use the readAsBytes method, which return a Future:

Img.Image image = Img.decodeImage(await pickedImage.readAsBytes());
  • Related