0

I have used Numbers Api for my application, but when pressed a button it show null on the screen. Also my API contains only String.

Here is my code for API:

String fact;
  Future fetchData() async {
    Response response;
    response = await get(Uri.https('numbersapi.com', 'random/trivia'));
    if (response.statusCode == 200) {
      print(response.statusCode);
      setState(() {
        fact = response.body;
      });
    }
  }

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

  @override
  Widget build(BuildContext context) { 
   .....

Since Text widget not accept null values, I converted it to toString() -

              fact.toString(),
              style: TextStyle(
                fontSize: 20.0,
                color: Colors.white,
              ),
            ),

But when fetchData() is passed in onPressed Property of the Elevated Button, it shows null on the screen.

How do I display a fact on screen instead of null?

Any help will be much appreciated :)

1 Answers1

0

Initially, the fact will be null until data is fetched. So either you can show some indicator that data is being fetched as following

fact == null ? Show Loading Message : Text(fact);

OR show an empty string like the following.

Text(fact ?? "")

For button

FlatButton(child: Text("Load"), onPressed: () async => await fetchData())

Edit:

Got the exact problem. The URL that you are trying to get the data from is not a secure URL. It is http not https

Hence try following while fetching data.

await get(Uri.http('numbersapi.com', 'random/trivia'))

Bad state: Insecure HTTP is not allowed by platform: Check this for Insecure HTTP Connection.

Pushpendra
  • 675
  • 5
  • 11