图像不显示在屏幕上

时间:2021-07-19 18:52:15

标签: flutter filepicker.io

我已经修改了我的代码。我以为我可以实现我愿意做的事情,但我仍然遇到问题。第一张图片很好,但是当我添加更多图片时,它们不会显示在屏幕上。这个想法是允许用户点击一个按钮来选择一个或多个图像。然后,他可以点击第二个按钮并添加一个 pfd 文件,就像在电子邮件中添加附件一样。然后,如果用户愿意,他可以点击第一个按钮并添加另一个图像。所有文件的列表应显示在屏幕上。我认为可能在某处缺少一个 set State。这是代码。我不明白我的错误在哪里。提前致谢。

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

List<PlatformFile>? _paths;
List<String> filesGB =[];
bool _loadingPath = false;
String fileExtension='';
String _fileName='';

// To access the pictures
  void _openPictureFileExplorer() async {
    setState(() => _loadingPath = true);

    try {
      _paths = (await FilePicker.platform.pickFiles(
        type: FileType.media,
        allowMultiple: true,
      ))?.files;

      if (_paths != null) {
        _paths!.forEach((element) {
        filesGB.add(element.path.toString());
        print(filesGB);
        print(filesGB.length);
        });
        setState(() {
        });
      }
      } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    } catch (ex) {
      print('$ex');
    }

    if (!mounted) return;
    setState(() {
      _loadingPath = false;
    });
  }

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: const Text('File Picker app'),
        ),
        body: Center(
            child: Padding(
              padding: const EdgeInsets.only(left: 10.0, right: 10.0),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(top: 20.0),

                      //#############
                      //Display card with button to select type of document
                      child: Card(
                          child:
                          Container(
                            // color: Colors.red,
                            alignment: Alignment.center,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                //Attachement
                                FlatButton(
                                  onPressed: () {},
                                  child:
                                  InkWell(
                                    child: Container(
                                      //  color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment
                                              .center,
                                          children: [
                                            Icon(Icons.attach_file),
                                            Text('Attachment'),
                                          ],
                                        )
                                    ),
                                    onTap: () async {
                                      fileExtension = 'pdf';
                                      _openDocumentFileExplorer();
                                    },
                                  ),
                                ),

                                //Photo
                                FlatButton(
                                  onPressed: () {},
                                  child:
                                  InkWell(
                                    child: Container(
                                      //   color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment
                                              .center,
                                          children: [
                                            Icon(Icons.add_a_photo_rounded),
                                            Text('Photo'),
                                          ],
                                        )
                                    ),
                                    onTap: () {
                                      fileExtension = 'jpeg';
                                      _openPictureFileExplorer();
                                    },
                                  ),
                                ),
                              ],
                            ),
                          )),
                    ),
                    Builder(
                      builder: (BuildContext context) => _loadingPath ?
                      Padding(
                        padding: const EdgeInsets.only(bottom: 10.0),
                        child:const CircularProgressIndicator(),
                      )

                      : filesGB.isNotEmpty ?
                      Column(
                            children: listOfCards(filesGB),
                      )
                     :Text('Nothing to display'),
                ),
    ]),)))));
  }
}

List<Widget> listOfCards(List<String> item){

  List<Widget> list = <Widget>[];
        ListView.builder(
           itemCount: filesGB.length,
           itemBuilder: (BuildContext ctxt, int index) {
         return new Container(
            height: 114,
            child: GestureDetector(
              child: Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  elevation: 10,
                  child: ClipPath(
                    clipper: ShapeBorderClipper(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(15))),

                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          height: 113, width: 113,
                          child: Image.file(File(item[i].toString()),
                            fit: BoxFit.fill,
                            width: double.infinity,),
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Text(item[i]
                                .split('/')
                                .last),
                          ),
                        ),
                      ],
                    ),
                  ),),
            ),
       );
  });
  return list;

}

2 个答案:

答案 0 :(得分:0)

首先,您不需要使用 for loop 来构建您的图片列表 只需使用 ListView.builder

但是关于你的问题,我认为这是因为你连续设置了选定的图片 然后将该行作为列的子行返回

所以你的图片水平对齐,列只显示垂直对齐的小部件

换句话说,你的列只有一个孩子,它是一个行 所以列尽可能显示图片,然后你只看到第一张图片。


为了解决这个问题,你应该在 listOfCards 函数中返回一个小部件列表

只需做这些简单的更改,我希望您的问题得到解决

将您的函数返回参数更改为 List<Widget>

Widget listOfCards(List<String> item) {

List<Widget> listOfCards(List<String> item) {

然后返回您的列表

return list;

你的专栏应该是这样的

Column(
   children: listOfCards(filesGB),
)

答案 1 :(得分:0)

我找到了一个可行的解决方案。它完成了我对图像的期望。我删除记录时仍然有问题,卡没有删除。我没有找到应该在哪里使用 setState。我会继续调查。

body: Center(
            child: Padding(
              padding: const EdgeInsets.only(left: 10.0, right: 10.0),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(top: 20.0),

                      //#############
                      //Display card with button to select type of document
                      child: Card(
                          child:
                          Container(
                            // color: Colors.red,
                            alignment: Alignment.center,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                //Attachement
                                FlatButton(
                                  onPressed: () {},
                                  child:
                                  InkWell(
                                    child: Container(
                                      //  color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment
                                              .center,
                                          children: [
                                            Icon(Icons.attach_file),
                                            Text('Attachment'),
                                          ],
                                        )
                                    ),
                                    onTap: () async {
                                      fileExtension = 'pdf';
                                      _openDocumentFileExplorer();
                                    },
                                  ),
                                ),

                                //Photo
                                FlatButton(
                                  onPressed: () {},
                                  child:
                                  InkWell(
                                    child: Container(
                                      //   color: Colors.white,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment
                                              .center,
                                          children: [
                                            Icon(Icons.add_a_photo_rounded),
                                            Text('Photo'),
                                          ],
                                        )
                                    ),
                                    onTap: () {
                                      fileExtension = 'jpeg';
                                      _openPictureFileExplorer();
                                    },
                                  ),
                                ),
                              ],
                            ),
                          )),
                    ),
                    Builder(
                      builder: (BuildContext context) => _loadingPath ?
                      Padding(
                        padding: const EdgeInsets.only(bottom: 10.0),
                        child:const CircularProgressIndicator(),
                      )

                      : filesGB.isNotEmpty ?
                      Column(
                        children: getList(),//[listOfCards(filesGB)],
                      )
                     :Text('Nothing to display'),
                ),
    ]),)))));
  }
}

List<Widget> getList() {
  List<Widget> childs = [];
  for (var i = 0; i < filesGB.length; i++) {
    childs.add(
        GestureDetector(
          onTap: (){
            print ("Pressed");
          },
          child: Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(15.0),
            ),
            elevation: 10,
            child: ClipPath(
              clipper: ShapeBorderClipper(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(15))),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                    height: 113,width: 113,
                    child: fileExtension == 'pdf'?
                    Image.asset('assets/logo_pdf.png',
                      // fit: BoxFit.fill,
                      //  width: double.infinity,
                    ):

                    Image.file(File(filesGB[i].toString()),
                      fit: BoxFit.fill,
                      width: double.infinity,),
                  ),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text(filesGB[i].toString().split('/').last,//_nameOfFile,//name,
                        style: TextStyle(fontWeight: FontWeight.bold),),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(right:25.0),
                    child: IconButton(onPressed: (){
                      //delete a record and the card displaying this record
                     // Delete the selected image
// This function is called when a trash icon is pressed
                      if (filesGB.length > 1) {
                        filesGB.removeAt(i);
                        print(filesGB);
                        setState(() {});
                      }
                    },

                      icon:Icon (Icons.delete, color: Colors.red,),),
                  )
                ],
              ),
            ),
            //subtitle: Text(path),
          ),
        ));}
  return childs;
}