Home > Blockchain >  How to call a function automatically on a specific page?
How to call a function automatically on a specific page?

Time:10-09

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,


        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.

CodePudding user response:

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

CodePudding user response:

Working with what you already have, you need to call setState affect fetching from the api.

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

But using a FutureBuilder is the best approach for handling what view to render based on the response success or failure.

  • Related