Search code examples
jsonflutterinitialization

How to fix "LateInitializationError: Field 'data' has not been initialized error"


I am working with a flutter app. I am trying to display data from a json.

I am stuck on the following error:

LateInitializationError: Field 'data' has not been initialized error

My main.dart file is as follows:

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

void main() => runApp(MaterialApp(
  home: HomePage(),
));

class HomePage extends StatefulWidget{
  @override
  HomePageState createState()=> new HomePageState();

}

class HomePageState extends State<HomePage>{
  final String url = "http://127.0.0.1:5000/restaurant";
  late List data;

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

  Future<String> getJsonData() async{
    var response = await http.get(Uri.parse(url));
    print(response.body);

    setState((){
      var convertDataToJson = json.decode(response.body);
      data = convertDataToJson['restaurant'];

    });

    return "success";
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar (
        title: new Text("Where to Eat")
      ),
      body: new ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index) {
          return new Container(
            child: new Center(
              child: new Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                new Card(
                  child: new Container(
                    child: new Text(data[index]['city']['details']),
                    padding: const EdgeInsets.all(20.0),
                  ),
                ),
              ],
            ),
           ),
          );
        },

      )
    );
  }
}

The line of code that is causing me issues is:

late List data;

I have tried to use the solution in this stackoverflow post here. However this did not work for me. It led to other errors that also caused the code not to compile.

How can I fix this error with my code correctly in order to display and parse the json data?

Here is the json I am using:

 {"city": "Al-Khobar",
  "details": [
   {
    "id": 1,
    "Area": "Near Corniche",
    "Restaurant": "Naranj Damascus Restaurant",
    "Street": "Firas Bin Al Nadr Street",
    "location link": "https:\\/\\/www.tripadvisor.com\\/Restaurant_Review-g298545-d22895043-Reviews-Naranj_Damascus_Restaurant-Al_Khobar_Eastern_Province.html#MAPVIEW",
    "City": "Al Khobar",
    "Zip": 34447,
    "Country": "Saudi Arabia",
    "phone": 966508446622,
    "meals": "Breakfast, Lunch, Dinner, Late Night",
    "cuisine": "International, Barbecue, Grill, Diner, Middle Eastern",
    "price range": "'$25 to $50"
   },

   {
    "id": 2,
    "Area": "Near Corniche",
    "Restaurant": "The Butcher Shop and Grill",
    "Street": "Prince Turkey Street",
    "location link": "https:\/\/www.tripadvisor.com\/Restaurant_Review-g298545-d10691837-Reviews-The_Butcher_Shop_and_Grill-Al_Khobar_Eastern_Province.html#MAPVIEW",
    "City": "Al Khobar",
    "Zip": " ",
    "Country": "Saudi Arabia",
    "phone": 966138085182,
    "meals": "Lunch, Dinner",
    "cuisine": "Steakhouse",
    "price range": "'$25 to $50"
   },
   {
    "id": 3,
    "Area": "Near Corniche",
    "Restaurant": "Kosebasi, Al Khobar",
    "Street": "Prince Turkey Street",
    "location link": "https:\/\/www.tripadvisor.com\/Restaurant_Review-g298545-d9874670-Reviews-Kosebasi_Al_Khobar-Al_Khobar_Eastern_Province.html#MAPVIEW",
    "City": "Al Khobar",
    "Zip": " ",
    "Country": "Saudi Arabia",
    "phone": 966138030089,
    "meals": "Lunch, Dinner",
    "cuisine": "Turkish, Middle Eastern, Barbecue",
    "price range": "'$25 to $50"
   },
   {
    "id": 4,
    "Area": "Near Corniche",
    "Restaurant": "Bun & Patty",
    "Street": "Prince Turkey Street Al Yarmouk",
    "location link": "https:\/\/www.tripadvisor.com\/Restaurant_Review-g298545-d8054714-Reviews-Bun_Patty-Al_Khobar_Eastern_Province.html#MAPVIEW",
    "City": "Al Khobar",
    "Zip": 344233213,
    "Country": "Saudi Arabia",
    "phone": " ",
    "meals": "Lunch, Dinner",
    "cuisine": "American, Fast Food",
    "price range": " "
   }
  ]
  },

 {"city": "Dammam",
  "details": [
   {
    "id": 5,
    "Area": "Near Corniche",
    "Restaurant": "Abu Nawas",
    "Street": "Al Adama – Prince Mansour Street",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g298547-d805085-Reviews-Abu_Nawas-Dammam_Eastern_Province.html#MAPVIEW",
    "City": "Dammam",
    "Zip": "31461",
    "Country": "Saudi Arabia",
    "phone": 966138266363,
    "meals": " ",
    "cuisine": "Lebanese, Mediterranean, Middle Eastern",
    "price range": "'$5 to $40"
   },
   {
    "id": 6,
    "Area": "Near Corniche",
    "Restaurant": "Heritage Village",
    "Street": "Prince Turkey Street",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g298547-d805123-Reviews-Heritage_Village-Dammam_Eastern_Province.html#MAPVIEW",
    "City": "Dammam",
    "Zip": " ",
    "Country": "Saudi Arabia",
    "phone": 96638090000,
    "meals": "Lunch, Dinner",
    "cuisine": "Middle Eastern, Vegetarian Friendly, Halal",
    "price range": "'$10 to $30"
   },
   {
    "id": 7,
    "Area": "Near Corniche",
    "Restaurant": "Manoosha Alreef",
    "Street": "Prince Faisal Bin Fahad Road Khobar North",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g298547-d10221865-Reviews-Manoosha_Alreef-Dammam_Eastern_Province.html#MAPVIEW",
    "City": "Dammam",
    "Zip": "34426",
    "Country": "Saudi Arabia",
    "phone": 966539222673,
    "meals": "Breakfast, Lunch, Dinner",
    "cuisine": "Bakeries, Lebanese, Fast Food",
    "price range": "'$25 to $50"
   },
   {
    "id": 8,
    "Area": "Near Corniche",
    "Restaurant": "American, Steakhouse",
    "Street": "Prince Mohammad Bin Fahad St.",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g298547-d2659493-Reviews-Steak_House-Dammam_Eastern_Province.html#MAPVIEW",
    "City": "Dammam",
    "Zip": 11372,
    "Country": "Saudi Arabia",
    "phone": "96638335468",
    "meals": "Lunch, Dinner",
    "cuisine": "American, Fast Food",
    "price range": "$10 to $35"
   }
  ]
  },

 {"city": "Jeddah",
  "details": [
   {
    "id": 9,
    "Area": "Blvd Mall",
    "Restaurant": "Nando's Mall Of Arabia",
    "Street": "Blvd Mall of Arabia Mall of Arabia, Gate No-5",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g295419-d20090707-Reviews-Nando_s_Mall_Of_Arabia-Jeddah_Makkah_Province.html#MAPVIEW",
    "City": "Jeddah",
    "Zip": "23532",
    "Country": "Saudi Arabia",
    "phone": 966503446623,
    "meals": "Breakfast, Lunch, Dinner",
    "cuisine": "Fast Food",
    "price range": "'$5 to $40"
   },
   {
    "id": 10,
    "Area": "Near Corniche",
    "Restaurant": "Heritage Village",
    "Street": "Prince Turkey Street",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g298547-d805123-Reviews-Heritage_Village-Dammam_Eastern_Province.html#MAPVIEW",
    "City": "Jeddah",
    "Zip": " ",
    "Country": "Saudi Arabia",
    "phone": 96638090000,
    "meals": "Lunch, Dinner",
    "cuisine": "Middle Eastern, Vegetarian Friendly, Halal",
    "price range": "'$10 to $30"
   },
   {
    "id": 11,
    "Area": "Near Corniche",
    "Restaurant": "Manoosha Alreef",
    "Street": "Prince Faisal Bin Fahad Road Khobar North",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g298547-d10221865-Reviews-Manoosha_Alreef-Dammam_Eastern_Province.html#MAPVIEW",
    "City": "Jeddah",
    "Zip": "34426",
    "Country": "Saudi Arabia",
    "phone": 966539222673,
    "meals": "Breakfast, Lunch, Dinner",
    "cuisine": "Bakeries, Lebanese, Fast Food",
    "price range": "'$25 to $50"
   },
   {
    "id": 12,
    "Area": "Near Corniche",
    "Restaurant": "American, Steakhouse",
    "Street": "Prince Mohammad Bin Fahad St.",
    "location link": "https://www.tripadvisor.com/Restaurant_Review-g298547-d2659493-Reviews-Steak_House-Dammam_Eastern_Province.html#MAPVIEW",
    "City": "Jeddah",
    "Zip": 11372,
    "Country": "Saudi Arabia",
    "phone": "96638335468",
    "meals": "Lunch, Dinner",
    "cuisine": "American, Fast Food",
    "price range": "$10 to $35"
   }
  ]
  }
]

Thanks


Solution

  • This is a basic example of how you can do it with FutureBuilder. It does not call http and works with a limited data, only simulates delay, but you can adjust it to your needs. You can run this on dartpad.dev.

    import 'package:flutter/material.dart';
    
    void main() => runApp(MaterialApp(
          home: HomePage(),
        ));
    
    class HomePage extends StatefulWidget {
      @override
      HomePageState createState() => HomePageState();
    }
    
    class HomePageState extends State<HomePage> {
      late final Future<List<Map<String, dynamic>>> _getJsonDataFuture;
      @override
      void initState() {
        super.initState();
        _getJsonDataFuture = getJsonData();
      }
    
      Future<List<Map<String, dynamic>>> getJsonData() async {
        // simulate delay
        await Future.delayed(const Duration(seconds: 2));
    
        var response = [
          {"id": 1, "name": "first"},
          {"id": 2, "name": "second"},
          {"id": 3, "name": "third"}
        ];
    
        return Future.value(response);
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(title: const Text("Where to Eat")),
            body: FutureBuilder<List<Map<String, dynamic>>>(
                future: _getJsonDataFuture,
                builder: (context, snapshot) {
                  // while loading
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const Center(child: CircularProgressIndicator());
                  }
                  // on error
                  if (snapshot.hasError) {
                    return Center(child: Text('Snapshot error: ${snapshot.error}'));
                  }
    
                  // on data received from future
                  if (snapshot.hasData && snapshot.data != null) {
                    return ListView.builder(
                        itemCount: snapshot.data!.length,
                        itemBuilder: (BuildContext context, int index) => Card(
                              child: Container(
                                child: Text(snapshot.data![index]['name']),
                                padding: const EdgeInsets.all(20.0),
                              ),
                            ));
                  }
    
                  // on missing data
                  return const Center(child: Text('Missing data'));
                }));
      }
    }