gpt4 book ai didi

dart - 如何修复 'String is not subtype of type widget' ?

转载 作者:IT王子 更新时间:2023-10-29 07:04:45 24 4
gpt4 key购买 nike

我正在尝试使用 GoogleTranslator 库翻译输入文本,但我收到一条错误消息,提示类型 String 不是类型 Widget 的子类型

我尝试创建一个函数来接收文本并返回翻译后的文本,并在应用程序主体上使用小部件

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

关于dart - 如何修复 'String is not subtype of type widget' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54312595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com