1

I using dart_meteor package

and it must be initiated in global scope main.dart

like this

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

and it got error:

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

from the documentation this package https://pub.dev/packages/dart_meteor must be

First, create an instance of MeteorClient in your app global scope so that it can be used anywhere in your project.

I need to call to server using static api, about newest version url

but I got error like this

so how to await http call (or synced http call) in main dart?

yozawiratama
  • 4,209
  • 12
  • 58
  • 106

2 Answers2

2

You cannot make the initializer for a global (or equivalently, static) variable await a Future; await is valid only within a function marked async. A global variable that is initialized asynchronously must be explicitly initialized later (or must itself be declared to be a Future).

If meteor must be global, in this case I'd just declare it to be late:

late MeteorClient meteor;

void main() async {
  meteor = MeteorClient.connect(url: await getUrl());

  runApp(const MyApp());
}

In this case, there is no chance for meteor to be accessed before it's initialized, so using late should be safe.

Also, I feel compelled to point out that your getUrl function is a pointless and less type-safe version of getUrl2. You should get rid of it.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
-1

Code:

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

use:

YourGlobalClass().getUrl();
YourGlobalClass().getUrl2();
YourGlobalClass().meteor();
  • This does not address the problem that `MeteorClient.connect` cannot be called with a `Future` as its argument. – jamesdlin Mar 09 '22 at 09:58