如何从另一个Dart文件中调用一个方法?

huangapple go评论51阅读模式
英文:

how to call a method from another dart file?

问题

在我的程序中,我想要在名为getPhoto()的方法内调用相同路径,以从其他文件或StatefulWidget获取"like"字段的路径。

英文:

in my programme i want to call the same path inside a methode called getPhoto()=>upload(statefulwidget) to other file or statefulwidget

Future getPhoto() async{

FirebaseFirestore fearbase = FirebaseFirestore.instance;

 Reference ref=FirebaseStorage.instance
 .ref()
 .child("${widget.user}/ProfileData")
 .child("Url_$postId");

 await ref.putFile(file!);
downloadUrl=await ref.getDownloadURL();

//  upload image to firestore
var list=[];
await fearbase.collection("users").doc(widget.user)
.collection("PostData").doc(ido)
.set({"PostUrl":downloadUrl,"ownerName":loggedInUser.username,"userId":loggedInUser.uid,"timestemp":postId,"PostId":ido,"like":FieldValue
.arrayUnion(list)})
.whenComplete(() => Fluttertoast.showToast(msg: "Image Uploaded successfully .i."));
// .then((DocumentReference ido) => ido.update({"PostId":ido.id}))

}

more specifically i want to get like field path from the other file

答案1

得分: 2

你可以使用回调函数来解决这个问题。

在使用时,可以按照以下方式传递函数:

getPhoto().then(upload);

或者

final downloadUrl = await getPhoto();
await upload(downloadUrl);
英文:

You can use callback function to solve this.

Future<String> getPhoto() async {
  Reference ref = FirebaseStorage.instance
      .ref()
      .child("${widget.user}/ProfileData")
      .child("Url_$postId");
  await ref.putFile(file!);
  return await ref.getDownloadURL();
  //  upload image to firestore
  
  // .then((DocumentReference ido) => ido.update({"PostId":ido.id}))
}

Future upload(String downloadUrl) async {
  FirebaseFirestore firebase = FirebaseFirestore.instance;
  var list = [];
  await firebase.collection("users").doc(widget.user)
      .collection("PostData").doc(ido)
      .set({
    "PostUrl": downloadUrl,
    "ownerName": loggedInUser.username,
    "userId": loggedInUser.uid,
    "timestemp": postId,
    "PostId": ido,
    "like": FieldValue
        .arrayUnion(list)
  })
      .whenComplete(() => Fluttertoast.showToast(msg: "Image Uploaded successfully .i."));
}

In usage, you can pass the function as follows

  getPhoto().then(upload);

Or

  final downloadUrl = await getPhoto();
  await upload(downloadUrl);

答案2

得分: 1

有多种方法可以做到这一点。

但简单的方法是创建一个类并在类内定义这个方法。

class Demo {
    static void getPhoto() {
        print("photo");
    }
}

然后你可以像这样访问它

Demo.getPhoto()
英文:

There are multiple ways to do this.

But the simple one is you can create a class and define this method within the class.

class Demo {
    static void getPhoto() {
        print("photo");
    }
}

Then your can access it like

Demo.getPhoto()

huangapple
  • 本文由 发表于 2023年2月18日 21:43:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75493742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定