Home > Software engineering >  lateInitializationError: Field 'variable' has not been initialized
lateInitializationError: Field 'variable' has not been initialized

Time:03-07

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

CodePudding user response:

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.

CodePudding user response:

Declare stringResponse as a nullable like so:

 String? stringResponse;

instead of:

  late String stringResponse;
  • Related