I don't have much experience with flutter.
I would like to use the language_tool library for Dart and Flutter (https://pub.dev/packages/language_tool)
I created this script in dart which prints to the console, the .message of the first item in the list.
void tool(String text) async {
var tool = LanguageTool();
var result = tool.check(text);
List correction = await result;
print(correction[0].message);
}
void main() {
tool('Henlo i am Gabriele');
}
After, I would like: correction [0] .message, to appear as text in my flutter app, but I don't know how I can do it as the tool() function has to return a Future .
How can I do?
class mainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Chat(),
);
}
}
class Chat extends StatefulWidget {
const Chat({Key? key}) : super(key: key);
@override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
String text = 'Henlo i am Gabriele';
Future<String> tool(String text) async {
var tool = LanguageTool();
var result = tool.check(text);
List correction = await result;
//print(correction[0].message);
return correction[0].message;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Text(text),
//Text(tool(text)),
],
),
),
);
}
}
I hope someone can help me, Thank you.
CodePudding user response:
You are getting the error because you are not using a FutureBuilder. Try using a FutureBuilder. You can solve it by wrapping your widget in a FutureBuilder.
check this post Flutter Future <String > cant be assigned to parameter type string
CodePudding user response:
tool()
is a Future
method. Try using FutureBuilder
.
FutureBuilder<String>(
future: tool(text),
builder: (context, snapshot) {
if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return Text(snapshot.data!);
}
return CircularProgressIndicator();
},
)
Check more about FutureBuilder
and When should I use a FutureBuilder?
CodePudding user response:
You need to use a FutureBuilder class:
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Text(text),
FutureBuilder<String>(
future: _calculation,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) =>
Text(tool(snapshot.data)),
),
],
),
),
);
}