flutterdartfuturelanguagetool

Future<String> as text in flutter


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.


Solution

  • 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?