Home > database >  How to await future in global main dart of flutter?
How to await future in global main dart of flutter?

Time:03-10

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?

CodePudding user response:

You cannot make the initializer for a global 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.

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.

CodePudding user response:

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();
  • Related