如何从Flutter中另一个类传递的函数中获取返回值?

时间:2019-08-08 03:24:54

标签: flutter dart

我有2页,分别是Screen1和Screen2

class Screen1 extends StatefulWidget {
  @override
  State createState() => new Screen1State();
}

class Screen1State extends State<Screen1> {
  testFunction() async {
    var response = await http.post(...);
    return "success";
  }

  @override
  void initState() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Screen2(handler: testFunction)
      ),
    );
  }
}

class Screen2 extends StatefulWidget {
  @override
  State createState() => new Screen2State();

  final Function handler;

  Screen1({@required this.handler});
}

class Screen2State extends State<Screen2> {
  @override
  void initState() {
    var test = widget.handler;
    print(test);    // the result will be instance of Future<dynamic> instead of "success"
  }
}

当我从Screen2上的Screen1调用传递的函数时,我需要获取“成功”值(该函数的返回值),但得到的却是“未来实例”(函数的类型)

所以我想问问是否有办法从另一个类获取传递函数的返回值?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试通过以下方式-


<?php

namespace App\Controller;

use App\Entity\Post;
use App\Entity\User;
use App\Entity\Rating;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;


class PostController extends AbstractController
{
   /**
    * @Route("post/delete/{id}")
    * @Method({"DELETE"})
    */
     public function delete(Request $request, $id)
     {

        $post = $this->getDoctrine()->getRepository(Post::class)->find($id);

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->remove($post);
        $entityManager->flush();

        $response = new Response();
        $response->send();
      }
}

使用class Screen2State extends State<Screen2> { @override void initState() { widget.handler().then((result) { print(result); // this will print "success" once the Future is complete }); } } 可以在Future.then()方法内提供一些代码,这些代码仅在then()完成时才执行。希望这会有所帮助!