Home > front end >  Flutter how to create package with function
Flutter how to create package with function

Time:02-18

I'm trying to make a package. I need to use async function, but I can't use it while building package.

Package Code:

class Sozluk {
  wiki(ceviri) async {
    var res = await http.Client()
          .get(Uri.parse('https://sozluk.gov.tr/gts?ara=$ceviri'));
      var body = res.body;
      var decoded = jsonDecode(body);
      var json = decoded[0];
      var sozlukanlam = json["anlamlarListe"][0]["anlam"];
      print(sozlukanlam);
      return sozlukanlam;
  }
}

Test Code:

void main() {
  test('köpek', () {
    final sozluk = Sozluk();
    var cevap = sozluk.wiki('köpek');
    print(cevap);
  });
}

The print I got:

Instance of 'Future<dynamic>'

CodePudding user response:

You code is missing a lot of pieces. Just because Dart allows you to write code like a sloppy web developer, does not mean you should. Dart is strongly typed, that is an advantage, please use it.

Problems:

  • ceviri has no explicit type.
  • wiki has no explicit return type.
  • wiki is not awaited
  • Your anonymous method is not async.

More information about Futures, async and await: What is a Future and how do I use it?

Fixing your code as good as possible:

class Sozluk {
  Future<TYPE_X> wiki(TYPE_Y ceviri) async {
    var res = await http.Client()
          .get(Uri.parse('https://sozluk.gov.tr/gts?ara=$ceviri'));
      var body = res.body;
      var decoded = jsonDecode(body);
      var json = decoded[0];
      var sozlukanlam = json["anlamlarListe"][0]["anlam"];
      print(sozlukanlam);
      return sozlukanlam;
  }
}

Test Code:

void main() {
  test('köpek', () async {
    final sozluk = Sozluk();
    var cevap = await sozluk.wiki('köpek');
    print(cevap);
  });
}

Please note that you need to fill in TYPE_X and TYPE_Y, I have no idea which datatypes best represent your data. Is it a number? A text? You decide.

CodePudding user response:

Yout question is unclear.

If you need to print

sozlukanlam

var in test function you need to await your wiki function becaus it is async.

So you could do somthing like that:

void main() {
  test('köpek', () async {
    final sozluk = Sozluk();
    var cevap = await sozluk.wiki('köpek');
    print(cevap);
  });
}

OR, if test function couldn't bee async

void main() {
  test('köpek', () {
    final sozluk = Sozluk();
    sozluk.wiki('köpek').then((sozlukanlam)=>print(cevap));
  });
}
  • Related