Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function automatically on a specific page?

I want to fetch a random quote from an API.
This is my function:

static Future<String?> getRandomQuote() async {
    Map<String, String> requestHeaders = {'Content-Type': 'application.json'};
    var url = Uri.https("api.quotable.io", "/random");
    var response = await client.get(url, headers: requestHeaders);
    if (response.statusCode == 200) {
      var data = jsonDecode(response.body);
      print(data["content"]);
      return data["content"].toString();
    } else {
      return "Sorry. Unable to Fetch Quote for you.".toString();
    }
  }

From this function, I want to get the string in another file:

String? _quote = "hey..";

  @override
  void initState() {
    super.initState();
    gotQuote();
  }

  void gotQuote() async {
    this._quote = await APIservice.getRandomQuote();
  }

  @override
  void dispose() {
    super.dispose();
  }

And, going to use this string value here,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


        child: Center(
          child: AnimatedTextKit(
            animatedTexts: [
              TyperAnimatedText(
                _quote!,
                textAlign: TextAlign.center,
                textStyle: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 25,
                  fontFamily: '',
                  wordSpacing: 2,
                  color: Colors.blueGrey,
                ),
              )
            ],
          ),
        ),      

But it does not show the output there. getRandomQuote() function properly as if it print value in console.

>Solution :

While you are using a future method, It would be better to use FutureBuilder

final future = APIservice.getRandomQuote();
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Column(
      children: [
        FutureBuilder<String?>(
          future: future,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Center(
                  child: AnimatedTextKit(
                animatedTexts: [
                  TyperAnimatedText(
                    snapshot.data ?? "",
                    textAlign: TextAlign.center,
                    textStyle: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 25,
                      fontFamily: '',
                      wordSpacing: 2,
                      color: Colors.blueGrey,
                    ),
                  )
                ],
              ));
            }
            if (snapshot.hasError) {
              return Text("Got error");
            }
            return CircularProgressIndicator();
          },
        ),

Find more about FutureBuilder

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading