0

I am trying to getting value from api as string. without widget testing, then i running i get an error: Error: XMLHttpRequest error.

What error's come from? here's my code:

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late String stringResponse;
  late List listResponse;

  Future fetchApi() async {
    final url = Uri.parse("https://www.thegrowingdeveloper.org/apiview?id=1");
    final response = await http.get(url);
    if (response.statusCode == 200) {
      setState(() {
        print(response.body);
        stringResponse = response.body;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    fetchApi();
    super.initState();
  }

  Widget build(BuildContext context) => Scaffold(
        body: (stringResponse == null)
            ? Container()
            : Text(stringResponse.toString()),
      );
}

from layout: display

Dendimuhmd
  • 53
  • 13
  • Your `initState` is asynchronous (`fetchApi` is, even if you don't wait for it). You need to use a `StreamBuilder`. See https://stackoverflow.com/questions/51901002/is-there-a-way-to-load-async-data-on-initstate-method – lrn Mar 06 '22 at 22:12
  • it's to keep using future or no? – Dendimuhmd Mar 07 '22 at 00:45

2 Answers2

0

You are getting error because stringResponse variable is late variable and while body is rendering, stringResponse variable is still not initilized. You can try give "" or null value as the initial value.

0

Declare stringResponse as a nullable like so:

 String? stringResponse;

instead of:

  late String stringResponse;
Josteve
  • 11,459
  • 1
  • 23
  • 35