How to fix 'String is not subtype of type widget'?
7,150
return translation as Widget;
should probably be
return Text(translation);
update
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"));
}
}
Author by
Mo0ohA
Updated on December 08, 2022Comments
-
Mo0ohA 23 minutes
I am trying to use GoogleTranslator library to translate input text, but i got an error that say type String is not subtype of type Widget
i tried to create a function that receive a text and return the translated text and used the widget on the body of the app
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"), ), ), ); } }
i expect the output to be in translated text in center of the screen
-
Günter Zöchbauer almost 4 yearsI don't know what
translate()
does, but I assume.toString();
on its return value is redundant. -
Mo0ohA almost 4 yearstranslate() is predefined method in GoogleTranslator Library
-
-
Mo0ohA almost 4 yearsreturn Text(translation); actually fixed the error but i the output that was displayed on the screen : Instance of Future<String>'
-
Günter Zöchbauer almost 4 yearsSorry, that code should be in a StatefulWidget. I'll have another look in a minute.