我正在尝试使用Google翻译库来翻译输入文本,但是我收到一个错误,说字符串类型不是小部件类型的子类型
我尝试创建一个接收文本并返回翻译文本的函数,并在应用程序正文中使用了小部件
import 'package:flutter/material.dart';
import 'package:translator/translator.dart';
void main() => runApp(MyApp());
Widget translator(String input) {
GoogleTranslator translator = GoogleTranslator();
String translation = translator
.translate("I would buy a car, if I had money.", from: 'en', to: 'ar')
.toString();
return translation as Widget;
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Translator'),
),
body: Center(
child: translator("Hello World"),
),
),
);
}
}
我希望输出是屏幕中央的翻译文本
return translation as Widget;
应该是
return Text(translation);
更新
import 'package:flutter/material.dart';
import 'package:translator/translator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Translator'),
),
body: Center(
child: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _translations = <String,String>{};
String translator(String input) {
if(_translations.containsKey(input)) {
return _translations[input];
} else {
_translate(input);
return input;
}
}
Future<void> _translate(String input) async {
GoogleTranslator translator = GoogleTranslator();
String translation = await translator
.translate("I would buy a car, if I had money.", from: 'en', to: 'ar');
setState(() => _translations[input] = translation);
}
@override
Widget build(BuildContext context) {
return Text(translator("Hello World"));
}
}