异步功能无法正常运行

时间:2019-11-01 21:05:47

标签: asynchronous flutter dart

我已经写了代码。它可以使用Google Cloud Translation API将单词从英语翻译成波兰语。我在打印所有翻译的单词时遇到问题。有些单词显示为空,其余单词则被翻译。 Photo with my problem.

这是我的 main.dart 代码:

import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
import 'dart:math';

import 'GoogleAPIservices/TranslationGoogleAPI.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: Center(
          child: RandomWords(),
        ),
      ),
    );
  }
}

class RandomWords extends StatefulWidget {
  @override
  RandomWordsState createState() => RandomWordsState();
}

class RandomWordsState extends State<RandomWords> {
  var _eNWords = <WordsWithTranslation>[];
  @override
  Widget build(BuildContext context) {
    for(int i=0;i<100;i++){
      Random rnd = new Random();
      _eNWords.add(WordsWithTranslation(nouns[rnd.nextInt(nouns.length)]));
    }

    return ListView.builder(
      itemCount: 100,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(_eNWords[index].toString()),
        );
      },
    );
  }
}

class WordsWithTranslation {
  String englishWord;
  String translatedWord;
  WordsWithTranslation(String wordInEnglish)  {
    this.englishWord = wordInEnglish;
    translateWord(wordInEnglish);
  }

  Future<void> translateWord(String wordInEnglish) async {
    TranslationGoogleAPI translation = TranslationGoogleAPI(wordInEnglish, "en", "pl");
    this.translatedWord = await translation.translateWord();
  }

  @override
  String toString() {
    return 'englishWord: $englishWord, translatedWord: $translatedWord';
  }

}

您可以看到我写了一个特殊的班级,用英语单词并将其翻译成波兰语。

这是我的 TranslationGoogleAPI.dart (具有已删除的API)代码:

import 'dart:convert';
import 'dart:core';
import 'package:http/http.dart' as http;
import 'package:untitled/GoogleAPIservices/parseTranslationFromGoogleAPI.dart';

class TranslationGoogleAPI {
  String _textToTranslate;
  String _countryCodeSource;
  String _translatedText;
  String _countryCodeTarget;
  String _API = 'DELETED :)';
  var _baseUrl = 'https://translation.googleapis.com/language/translate/v2/?q=';
  TranslationGoogleAPI(String textToTranslate, String countryCodeSource,
      String countryCodeTarget) {
    this._textToTranslate = textToTranslate;
    this._countryCodeTarget = countryCodeTarget;
    this._countryCodeSource = countryCodeSource;
    this._translatedText = "test";
  }


  Future<String> translateWord()  async {
    final response = await http.get(_baseUrl +
        _textToTranslate +
        "&source=" +
        _countryCodeSource +
        "&target=" +
        _countryCodeTarget +
        "&key=" +
        _API);
    if (response.statusCode == 200) {
      parseTranslationFromGoogleAPI a =
      parseTranslationFromGoogleAPI.fromJson(json.decode(response.body));
      this._translatedText = a.toString();
      this._translatedText=_translatedText.substring(1,_translatedText.length-1); // delete  signs: []
      return _translatedText;
    } else {
      throw Exception('Failed to load post');
    }
  }
}

这是我的 parseTranslationFromGoogleAPI.dart ,用于解析JSON中的响应:

    class parseTranslationFromGoogleAPI {
  Data _data;

  parseTranslationFromGoogleAPI({Data data}) {
    this._data = data;
  }

  Data get data => _data;
  set data(Data data) => _data = data;

  parseTranslationFromGoogleAPI.fromJson(Map<String, dynamic> json) {
    _data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this._data != null) {
      data['data'] = this._data.toJson();
    }
    return data;
  }

  @override
  String toString() {
    return _data.toString();
  }


}

class Data {
  List<Translations> _translations;

  Data({List<Translations> translations}) {
    this._translations = translations;
  }

  List<Translations> get translations => _translations;
  set translations(List<Translations> translations) =>
      _translations = translations;

  Data.fromJson(Map<String, dynamic> json) {
    if (json['translations'] != null) {
      _translations = new List<Translations>();
      json['translations'].forEach((v) {
        _translations.add(new Translations.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this._translations != null) {
      data['translations'] = this._translations.map((v) => v.toJson()).toList();
    }
    return data;
  }

  @override
  String toString() {
    return _translations.toString();
  }
}

class Translations {
  String _translatedText;

  Translations({String translatedText}) {
    this._translatedText = translatedText;
  }

  String get translatedText => _translatedText;
  set translatedText(String translatedText) => _translatedText = translatedText;

  Translations.fromJson(Map<String, dynamic> json) {
    _translatedText = json['translatedText'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['translatedText'] = this._translatedText;
    return data;
  }

  @override
  String toString() {
    return _translatedText;
  }

}

我无法正确显示所有单词。

0 个答案:

没有答案