如何从颤振中的另一个小部件函数调用添加函数?

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

我想从另一个按钮小部件调用另一个小部件的添加功能。

当我点击按钮小部件时,我想刷新 phtoselector。

所以当我点击按钮小部件时,我想调用 phtoselector 的 'add(photoDats)'

我该怎么做?

如果你能告诉我,有经验的人将不胜感激。

[我想叫这个]

   add(photoDatas)

[我想在这里调用 'add(photoDatas)'(当我按下按钮小部件时)]

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

[这是完整代码]

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

}

这是每个 Flutter 开发人员面临的最常见问题,但还没有解决此问题的详细文档。

您正在使用一个库 photo_selector,它有一个处理函数 photoSelectorHandler,它反过来提供您的 add 函数。

我认为这样的代码应该对您有所帮助:

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
    ...
 }
)

])

)
}
}

我没有使用 photo_selector 库,但我假设每次 select 一张照片时都会调用它的 handler.onAdd 函数。