mercredi 9 juin 2021

Condition for three buttons when pressed, it should call different functions and display text in same text widget in Flutter

I have made a number fact generating application,

I have three buttons Random Trivia, Random Year, Random Date. When Random trivia is clicked it generates random fact about that number, when random Year is clicked it generates random fact about year and similarly for Random date.

I want the condition for my buttons that- if Random Year is pressed, it should call the year function and display the fact in text widget & if Random Date is pressed, it should call the date function and display the fact in SAME text widget, and similarly for Random Trivia.

This is the function for Random Trivia-

void fetchDataForTrivia() async {
    http.Response response;
    response = await http.get(Uri.http('numbersapi.com', 'random/trivia'));
    if (response.statusCode == 200) {
      print(response.statusCode);
      print(response.body);
      setState(() {
        factTrivia = response.body;
      });
    }
  }

Function for Random Year-

void fetchDataForYear() async {
    http.Response response;
    response = await http.get(Uri.http('numbersapi.com', 'random/year'));
    if (response.statusCode == 200) {
      print(response.statusCode);
      print(response.body);
      setState(() {
        factYear = response.body;
      });
    }
  }

Function for Random Date -

void fetchDataForDate() async {
    http.Response response;
    response = await http.get(Uri.http('numbersapi.com', 'random/date'));
    if (response.statusCode == 200) {
      print(response.statusCode);
      print(response.body);
      setState(() {
        factDate = response.body;
      });
    }
  }

This is Text Widget, for now it just displays Random Trivia-

Text(factTrivia.toString(),
                  style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.purple[400],
                  )),

And these are the buttons for 'RandomTrivia', 'Random Year', and 'Random Date' respectively-

ElevatedButton(
                  onPressed: () {
                    fetchDataForTrivia();
                  },
------------------

ElevatedButton(
                  onPressed: () {
                    fetchDataForYear();
                  },

------------------

ElevatedButton(
                  onPressed: () {
                    fetchDataForDate();
                  },
-----------------

Any help will be much appreciated:)

Aucun commentaire:

Enregistrer un commentaire