Flutter / Dart异步未等待

时间:2018-12-05 12:15:58

标签: dart async-await flutter future

我正在构建我的第一个Flutter应用程序,并且遇到了一些异步问题。

当我的应用程序执行时,我希望它请求权限并等待它们被授予。我的main()函数如下所示:

RED=(255,0,0)
BLACK=(0,0,0)
WHITE =(255,255,255)
GREEN = (0,255,0)
player_health = 10
enemy_health = 10
collision_counter = 0
attack_counter = 0
attack = False

import pygame

#Creating screen and sprites
all_sprites_list = pygame.sprite.Group()
all_enemies_list = pygame.sprite.Group()

pygame.init()

screen = pygame.display.set_mode((1,1))

class Sprites(pygame.sprite.Sprite):

    def __init__(self,x,y,img):
        super().__init__()

        #Colour and position
        #Set the background colour and set the image to be transparent
        self.image = pygame.Surface([x, y])
        self.image.fill(WHITE)
    self.image.set_colorkey(WHITE)

    #Or using an image
    self.image = pygame.image.load(img).convert_alpha()

    #Fetch a rectangle that is the same size
    self.rect = self.image.get_rect()

    self.mask = pygame.mask.from_surface(self.image)


def AI(self,charX):

    #If the player is on the left
    if self.rect.x < charX:
        self.rect.x +=  1

    #On right
    if self.rect.x > charX:
        self.rect.x -= 1

def update(self,charX):
    self.AI(charX)


img = "BadCrab.png"
#Creating the first AI sprite with width,height,colour and x,y position
AI1 = Sprites(30,20,img)
AI1.rect.x = 0
AI1.rect.y = 150
#Adding to to the necessary groups
all_enemies_list.add(AI1)

#Creating the character sprite with width,height,colour and x,y position
char = Sprites(30,20,"Crab.fw.png")
char.rect.x = 150
char.rect.y = 150
#Adding to to the necessary group
all_sprites_list.add(char)

screen = pygame.display.set_mode((800,400))
clock = pygame.time.Clock()
counter = 0

while True:
    pygame.event.pump()
    screen.fill(BLACK)
    clock.tick(60)
    pygame.event.pump()
    keys = []

    #Getting the keys which are pressed down
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            keys.append(event)

    #Converting the array to a string so it can be searched
    keys=str(keys)

    #Using the keys numbern value to determine if it has been pressed
    #Left arrow = 276
    if "276" in keys:
        char.rect.x -= 40

    #Right arrow = 275
    elif "275" in keys:
        char.rect.x += 40

    counter += 1
    #Space = 32
    if "32" in keys:
        counter = 0
        #Removing orignal sprite and then changing it to the attack sprite
        all_sprites_list.remove(char)
        char = Sprites(30,20,"Crab_attack.fw.png")
        char.rect.y = 150
        char.rect.x = charX
        all_sprites_list.add(char)
        attack = True
    #Allwoing the attack sprite to be drawn before replaced by original sprite
    if counter == 12:
        all_sprites_list.remove(char)
        char = Sprites(30,20,"Crab.fw.png")
        char.rect.y = 150
        char.rect.x = charX
        all_sprites_list.add(char)
        counter = 0
        attack = False

    charX = char.rect.x
    all_enemies_list.update(char.rect.x)
    all_enemies_list.draw(screen)
    all_sprites_list.draw(screen)
    pygame.display.flip()

    #Checking for collisions
    collisions = pygame.sprite.groupcollide(all_sprites_list, all_enemies_list,False,False)
    print(str(collisions))

Permission Manager类的get_permissions()函数使用Flutter Simple Permissions软件包检查并询问权限。

import 'permission_manager.dart' as Perm_Manager;

void main() async
{
  //Ensure valid permissions
  Perm_Manager.Permission_Manager pm = Perm_Manager.Permission_Manager();
  var res = await pm.get_permissions();
  print(res);

  return runApp(MyApp());
} 

当我运行应用程序时,它不会等待功能按预期完成,并会在更新Future之前打印“ res”的值。

import 'package:simple_permissions/simple_permissions.dart';
import 'dart:io' as IO;
import 'dart:async';

class Permission_Manager {
  /* Get user permissions */

  Future<bool> get_permissions() async
  {
    //Android handler
    if (IO.Platform.isAndroid)
    {
        //Check for read permissions
        SimplePermissions.checkPermission(Permission.ReadExternalStorage).then((result)
        {
          //If granted
          if (result)
            return true;

          //Otherwise request them
          else
          {
            SimplePermissions.requestPermission(Permission.ReadExternalStorage)
            .then((result)
            {
              // Determine if they were granted
              if (result == PermissionStatus.authorized)
                return true;
              else
                IO.exit(0); //TODO - display a message
            });
          }
        });
    }

    else
      return true;
  }
}

Future在函数中途返回一个值!有人知道我在做什么错吗?

2 个答案:

答案 0 :(得分:3)

要等待某件事,您将来必须调用await而不是.then

final result = await future;
// do something

代替

future.then((result) {
  // do something
});

如果您真的要使用.then,则可以等待生成的将来:

await future.then((result) {
  // do something
});

只要确保在使用嵌套异步调用时,在每个异步调用上使用async关键字即可:

await future.then((result) async{
    // do something
    await future.then((result_2) {
       // do something else
    });
});

答案 1 :(得分:-2)

使其正常工作。该问题似乎可以通过使用Completer解决:

import 'package:simple_permissions/simple_permissions.dart';
import 'dart:io' as IO;
import 'dart:async';

class Permission_Manager {
  /* Get user permissions */

  final Completer c = new Completer();

  Future get_permissions() async
  {

    //Android handler
    if (IO.Platform.isAndroid)
    {
        //Check for read permissions
        SimplePermissions.checkPermission(Permission.ReadExternalStorage).then((result)
        {
          //If granted
          if (result)
          {
            c.complete(true);
          }
          //Otherwise request them
          else
          {
            SimplePermissions.requestPermission(Permission.ReadExternalStorage).then((result)
            {
              // Determine if they were granted
              if (result == PermissionStatus.authorized)
              {
                c.complete(true);
              }
              else
              {
                IO.exit(0); //TODO - display a message
              }
            });
          }
        });
    }

    else
    {
      c.complete(true);
    }

    return c.future;
  }

}