代码之家  ›  专栏  ›  技术社区  ›  yozawiratama

如何在全球的主飞镖中等待未来?

  •  0
  • yozawiratama  · 技术社区  · 3 年前

    我使用dart_meteor软件包

    它必须在全球范围内发起 main.dart

    这样地

    import 'package:flutter/material.dart';
    import 'package:dart_meteor/dart_meteor.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    Future getUrl2() async {
      Uri myUrl = Uri.http('myurl.id', '/geturl.php');
    
      try {
        http.Response response = await http.get(myUrl );
        return response.body;
      } catch (e) {
        throw (e);
      }
    }
    
    MeteorClient meteor = MeteorClient.connect(url: getUrl());
    
    getUrl() async {
      String url = await getUrl2();
      return url;
    }
    
    void main() {
      runApp(const MyApp());
    }
    

    结果出现了错误:

    _TypeError (type 'Future<dynamic>' is not a subtype of type 'String')

    从该软件包的文档中 https://pub.dev/packages/dart_meteor 必须是

    首先,在你的应用程序global scope中创建MeteorClient实例,这样它就可以在你的项目中的任何地方使用。

    我需要使用静态api调用服务器,关于最新版本的url

    但我犯了这样的错误

    那么,如何在主dart中等待http调用(或同步http调用)?

    2 回复  |  直到 3 年前
        1
  •  2
  •   jamesdlin    3 年前

    不能为全局(或等效)创建初始值设定项, static )变数 await A. Future ; 等候 仅在标记为 async 。异步初始化的全局变量以后必须显式初始化(或必须将其本身声明为 将来 )。

    如果 meteor 必须是全球性的,在这种情况下,我只是宣布它是全球性的 late :

    late MeteorClient meteor;
    
    void main() async {
      meteor = MeteorClient.connect(url: await getUrl());
    
      runApp(const MyApp());
    }
    

    在这种情况下,没有机会 流星 在初始化之前被访问,所以使用 晚的 应该是安全的。

    此外,我不得不指出,你的 getUrl 函数是 getUrl2 .你应该把它扔掉。

        2
  •  -1
  •   Phạm Anh Tú    3 年前

    代码:

      class YourGlobalClass {
        Future<String> getUrl2() async {
          Uri myUrl = Uri.http('myurl.id', '/geturl.php');
    
          try {
            http.Response response = await http.get(myUrl);
            return response.body;
          } catch (e) {
            throw (e);
          }
        }
    
        Future<MeteorClient> meteor() async {
          final meteor = MeteorClient.connect(url: await getUrl());
          return meteor;
        }
    
        Future<String> getUrl() async {
          String url = await getUrl2();
          return url;
        }
      }
    

    使用:

    YourGlobalClass().getUrl();
    YourGlobalClass().getUrl2();
    YourGlobalClass().meteor();