Search code examples
flutterflutter-layoutflutter-dependenciesflutter-web

How to call add function from another widget's funtion in flutter?


I want to call another widget's add funtion from another button widget.

When i click button widget i want to refresh phtoselector.

So When i click button widget i want to call phtoselector's 'add(photoDats)'

How can i do that?

Anyone with experience would appreciate it if you could let me know.

[I wnat to call this ]

   add(photoDatas)

[I want to call 'add(photoDatas)' in here(when i press button widget)]

    onPressed: () async {
          ''''some where ''''
          }

[This is full code]

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:nullcodebranch1/certification_page.dart';
import 'package:photo_selector/photo_selector.dart';
import 'Login2_dark/widgets/button_widget.dart';
import 'package:get/get.dart';



class VacantPage3 extends StatefulWidget {


  //const VacantPage3(this.user, {Key? key}) : super(key: key);

  @override
  _VacantPage3State createState() => _VacantPage3State();
}


class _VacantPage3State extends State<VacantPage3> {
  GlobalKey<_VacantPage3State> _key = GlobalKey<_VacantPage3State>();
  List<PhotoData> photos = [

  ];

  late File arg1;
  var arg2;



  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    //final File image = await ImagePicker.pickImage(source: imageSource);
    final File? _saveimage;
    var value;

    return Scaffold(

      appBar:
      AppBar(
        backgroundColor: Color(0xff151f2c),
        title: Text('사진 선택기',
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),),

      ),
      body: Column(
        mainAxisSize: MainAxisSize.min,

        children: [
          Flexible(
            child: Container(
              key: _key,
              padding: EdgeInsets.all(10),
              //width: double.infinity,
              width: screenWidth,
              child: PhotoSelector(
                photoDatas: photos,
                photoSelectorLayout: (layout) {
                  layout.edit = true;
                  layout.maxCount = 4;
                  layout.scroll = true;
                  layout.horizontalSpacing = 5.0;
                  layout.verticalSpacing = 5.0;
                  layout.column = 4;
                },
                photoSelectorHandler: (handler) {
                  handler.onAdd = (add) {
                    ImagePicker().pickImage(source: ImageSource.gallery).then((value) {
                      List<PhotoData> photoDatas = [];
                      /*    value?.forEach((element) {
                        PhotoData photoData = PhotoData(
                          imageData: File(element.path),
                        );
                        photoDatas.add(photoData);
                      });*/
                      PhotoData photoData = PhotoData(
                        imageData: File(value!.path),
                      );
                      photoDatas.add(photoData);
                      
                      add(photoDatas);
                     
           
                      // _key=add(photoDatas);
                      //  widget.key.;
                      //widget.key.

                    });
                  };
                  handler.onDelete = (data, datas) {
                    print("삭제된 사진 데이터:${data.imageData}");
                    print("삭제된 사진 수:${datas.length}");
                  };
                  handler.onPreview = (data, datas) {
                    print("현재 미리 본 사진 데이터:${data.imageData}");
                    print("현재 미리 본 사진의 색인:${datas.indexOf(data)}");
                    print("미리 본 사진 수:${datas.length}");
                    print(value);
                 //   print(value[0]["backValue"]);
                   // print(value[0]['backValue']);
                  };
                },
              ),
            ),
          ),

          ButtonWidget(
              text:  "인증하기" ,
              backColor: [
                Colors.black,
                Colors.black,
              ],
              textColor: const [
                Colors.white,
                Colors.white,
              ],
              onPressed: () async {

                value = await Get.to(CertificationPage());
                print('언제 들어오니');
                if(value[0]["backValue"]!=null)
                {
                  print('null이 아니다');
                  PhotoSelector(photoDatas: photos);
                  List<PhotoData> photoDatas = [];
                  arg1 = value[0]["backValue"];
                  print(arg1);

                  PhotoSelector(photoDatas: photos,photoSelectorHandler:
                      (handler) {
                    PhotoData photoData = PhotoData(
                      imageData: value[0]["backValue"],
                    );
                    photos.add(photoData);

                  }
                  );
                  //add(photos);
                  print("추가된 사진 수:${photos.length}");
                }else{
                  print('null임');
                }
              }
          ),
        ],
      ),

    );
  }



  void _refresh(void Function(List<PhotoData> photoDatas) add, List<PhotoData> photoDatas){
    print('후...쉽지 않네..');
    add(photoDatas);
  }

}

Solution

  • This is the most common problem every flutter developer faces, yet there are no detailed documentation that address this issue.

    You are using a library photo_selector, which has a handler function photoSelectorHandler which in turns provide your add function.

    I think a code like this should help you:

    class _VacantPage3State extends State<VacantPage3> {
    ...
    var _add; ///////// 1. here we have added a private variable _add
    
    
    @override
    Widget build(BuildContext context) {
    return Scaffold(
     ...
    Column(children:[
     Container(
       ...
       child: PhotoSelector(
               ...
               photoSelectorHandler: (handler) {
                      handler.onAdd = (add) {
                           this._add=add; ///////// 2. here we have assigned it
                           ...
                      }
               }
    
              )
    
    
     ),
    
    ButtonWidget(
     onPressed: ()async{
        /////// 3. here you can use this._add as add functon
        ...
     }
    )
    
    ])
    
    )
    }
    }
    

    I have not used photo_selector lib, but I assume that its handler.onAdd function get called each time you select a photo.

    enter image description here