【问题标题】:Image picker not get file Flutter图像选择器无法获取文件 Flutter
【发布时间】:2022-01-16 14:02:54
【问题描述】:

下面的颤动代码允许我从图库中选择图像并将其插入可变文件文件中,但是当我运行代码并尝试打印文件值时它始终为空,我该如何解决这个问题?

飞镖代码:

Future getImage() async {
    PickedFile pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
    );
    if (pickedFile != null) {
      print("file picked");
      file = File(pickedFile.path);
    }
    else{
      print("File not picked");
    }

  }

完整类代码:

File file;
class DocumentiImpiantoView extends StatefulWidget {
  const DocumentiImpiantoView(this.imp);
  final Impianto imp;
  @override
  _DocumentiImpiantoViewState createState() => _DocumentiImpiantoViewState();
}

class _DocumentiImpiantoViewState extends State<DocumentiImpiantoView> {
  TextEditingController _searchController = new TextEditingController();
  Timer timer;

  final picker = ImagePicker();

  _DocumentiImpiantoViewState() {
    timer = Timer.periodic(Duration(seconds: 6), (Timer t) => updateui());
    getData();
  }

  Future<bool> getData() async {
    listadocumenti = await Documento.load(widget.imp);
    return true;
  }

  Future getImage() async {
    PickedFile pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
    );
    if (pickedFile != null) {
      print("file picked");
      file = File(pickedFile.path);
    }
    else{
      print("File not picked");
    }

  }

  updateui() async {
    var values = await Documento.load(widget.imp);
    setState(() {
      listadocumenti = values;
    });
  }

  selectfile() async {
    print("Seleziono il file");
    FilePickerResult result = await FilePicker.platform.pickFiles();
    if (result != null) {
      print("Salvataggio file");
       file = File(result.files.single.path);
    } else {
      // User canceled the picker
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: getData(),
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return !snapshot.hasData
            ? new Container()
            : Scaffold(
                body: getBody(),
              );
      },
    );
  }

  //Funzione che apre la visualizzazione del file con link
  openfile() {
    //await launch(URL, forceSafariVC: false);
  }

  goback(BuildContext context) {
    final gr = new DettagliImpiantoView(widget.imp);
    Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => gr));
  }

  //Upload file su impianto
  uploadfile() async {
    print("caricamento file");
    if(file==null){
      print("File è null");
    }
    else {
      try {
        //List<int> fileInByte = file.readAsBytesSync();
        final bytes = File(file.path).readAsBytesSync();
        String base64Image = "data:image/png;base64," + base64Encode(bytes);
        print("caricamento file 2");
        Impianto.uploadfile(widget.imp, base64Image, file.path);
        updateui();
      } catch (err) {
        print("Errore: " + err);
      }
    }
  }

  Widget getBody() {
    return SafeArea(
        child: ListView(
      padding: EdgeInsets.only(left: 20, right: 20, top: 15),
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            GestureDetector(
              onTap: () {
                goback(context);
              },
              child: Icon(Icons.arrow_back),
            ),
            Text(
              "Documenti",
              style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
            ),
            Icon(Icons.add)
          ],
        ),
        SizedBox(
          height: 10,
        ),
        SizedBox(
          height: 30,
        ),
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(right: 20),
                child: Column(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        uploadfile();
                      },
                      child: Container(
                        width: 70,
                        height: 70,
                        decoration: BoxDecoration(shape: BoxShape.circle, color: grey),
                        child: Center(
                          child: Icon(
                            LineIcons.plus,
                            size: 33,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    GestureDetector(
                        onTap: () {
                          uploadfile();
                        },
                        child: SizedBox(
                          width: 75,
                          child: Align(
                              child: Text(
                            'Upload File',
                            overflow: TextOverflow.ellipsis,
                          )),
                        )),
                  ],
                ),
              ),
              Row(
                  children: List.generate(optionsList.length, (index) {
                return Padding(
                  padding: const EdgeInsets.only(right: 20),
                  child: Column(
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          if (optionsList[index]["name"] == "Documenti") {
                            selectfile();
                          } else {
                            getImage();
                          }
                        },
                        child: Container(
                          width: 75,
                          height: 75,
                          child: Stack(
                            children: <Widget>[
                              Container(
                                  decoration: BoxDecoration(
                                      shape: BoxShape.circle, border: Border.all(color: blue_story, width: 3)),
                                  child: Padding(
                                    padding: const EdgeInsets.all(3.0),
                                    child: Container(
                                      width: 90,
                                      height: 90,
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(8.0),
                                        child: Image.asset(optionsList[index]['img'], width: 30, height: 30),
                                      ),
                                    ),
                                  )),
                              Positioned(
                                top: 48,
                                left: 52,
                                child: Container(
                                  width: 20,
                                  height: 20,
                                  decoration: BoxDecoration(
                                      color: online,
                                      shape: BoxShape.circle,
                                      border: Border.all(color: white, width: 3)),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      SizedBox(
                        width: 90,
                        child: Align(
                            child: Text(
                          optionsList[index]['name'],
                          overflow: TextOverflow.ellipsis,
                        )),
                      )
                    ],
                  ),
                );
              }))
            ],
          ),
        ),
        SizedBox(
          height: 30,
        ),
        Column(
          children: List.generate(listadocumenti.length, (index) {
            return InkWell(
              onTap: () {},
              child: Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Row(
                  children: <Widget>[
                    Container(
                      width: 75,
                      height: 75,
                      child: Stack(
                        children: <Widget>[
                          Container(
                            decoration:
                                BoxDecoration(shape: BoxShape.circle, border: Border.all(color: blue_story, width: 3)),
                            child: Padding(
                              padding: const EdgeInsets.all(3.0),
                              child: Container(
                                width: 90,
                                height: 90,
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(8.0),
                                  child: Image.asset("assets/images/rapportini.png"),
                                ),
                              ),
                            ),
                          ),
                          Positioned(
                            top: 48,
                            left: 52,
                            child: Container(
                              width: 20,
                              height: 20,
                              decoration: BoxDecoration(
                                  color: online, shape: BoxShape.circle, border: Border.all(color: white, width: 3)),
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(
                      width: 20,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          listadocumenti[index].Utente,
                          style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),
                        ),
                        SizedBox(
                          height: 5,
                        ),
                        SizedBox(
                          width: MediaQuery.of(context).size.width - 135,
                          child: Text(
                            listadocumenti[index].IdDoc.toString(),
                            style: TextStyle(fontSize: 15, color: black.withOpacity(0.8)),
                            overflow: TextOverflow.ellipsis,
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            );
          }),
        )
      ],
    ));
  }
}

【问题讨论】:

  • 你在哪里打印file
  • 我不是打印文件,请检查是否在功能uploadfile @Josteve上选择了它

标签: flutter dart flutter-dependencies


【解决方案1】:

在您的代码中有几个问题。首先 imagePicker 将图像选择为 Xfile,但您将其分配为文件。像这样编辑您的 getImage 函数。有时,如果图像尺寸太大,可能会出现问题。在这种情况下,压缩图像可能会对您有所帮助。

File? _imageFile;
Future<void> getImage() async {
 XFile? pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
 if (pickedFile != null) {
   File selected = File(pickedFile.path);
  _imageFile = selected;
  compressFile(_imageFile!);
 }
}

压缩文件功能

Future<void> compressFile(File file) async {
 if (file.lengthSync() < 1000000) {
  setState(() {
    _imageFile = file;
  });
} else {
ImageProperties properties =
    await FlutterNativeImage.getImageProperties(file.path);
    File result = await FlutterNativeImage.compressImage(file.path,
    quality: 95,
    targetWidth: 600,
    targetHeight: (properties.height! * 600 / 
    properties.width!).round());
    setState(() {
     _imageFile = result;
   });
 }
NavigationService.getCurrentState()?.pop(_imageFile);
}

【讨论】:

  • 我没有方法pickImage我有getimage
  • 我使用了 pickImage 因为 getImage 现在已被弃用。使用更新的包总是一个好习惯。
猜你喜欢
  • 2020-04-15
  • 2022-08-19
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 2020-09-18
相关资源
最近更新 更多