Images don't displayed on screen

301 views Asked by At

I have modified my code. I thought I could achieve what I am willing to do but I am still having an issue. The first image is fine, but when I am adding more images, they don't display to the screen. The idea is to allow the user to click on a button to select one or several images. Then, he can tap on a second button and add one pfd file, it is like adding attachment in email.Then, if the user wants he can tap on the first button and add an other image. The list of all the documents should be displayed on the screen. I though that maybe a set State is missing somewhere. Here is the code. I do not understand where is my mistake. Thank you in advance.

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

There are 2 answers

7
Amir On

first of all, you don't need to use for loop for building your pictures list just use ListView.builder

but about your problem, I think it happens because you set selected pictures in a row then return that row as a child of your column

so your pictures align horizontally and column just show widgets in vertical aligns

in other words, your column just have one child, and its a Row so column just show pictures as possible then you just see the first picture.


for solving this problem you should return a list of widgets in the listOfCards function

just do these simple changes and I hope your problem solved

change your function return parameter to List<Widget>

Widget listOfCards(List<String> item) {

to

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

then just return your list

return list;

and your column should look like this

Column(
   children: listOfCards(filesGB),
)
0
Laurent Thomas On

I have find a working solution. It does what I was expecting with image. I still have a problem when I delete a record, the card is not removed. I do not find where I should use the setState. I will continue to investigate.

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;
}