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

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

我正在使用 flutter 应用程序。 我正在尝试显示来自 json.

的数据

我遇到了以下错误:

LateInitializationError: Field 'data' has not been initialized error

我的main.dart文件如下:

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),
                  ),
                ),
              ],
            ),
           ),
          );
        },

      )
    );
  }
}

导致我出现问题的代码行是:

late List data;

我已经尝试使用这个 Whosebug post 中的解决方案。 但是,这对我不起作用。它导致了其他错误,也导致代码无法编译。

如何使用我的代码正确修复此错误,以便显示和解析 json 数据?

这是我正在使用的json:

 {"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": "' to "
   },

   {
    "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": "' to "
   },
   {
    "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": "' to "
   },
   {
    "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": "' to "
   },
   {
    "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": "' to "
   },
   {
    "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": "' to "
   },
   {
    "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": " to "
   }
  ]
  },

 {"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": "' to "
   },
   {
    "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": "' to "
   },
   {
    "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": "' to "
   },
   {
    "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": " to "
   }
  ]
  }
]

谢谢

late List data; 应更改为 List? data;。如果某物是 non-nullable 但 late,则需要开发人员确保此变量在使用前已初始化。 由于在build方法中使用,在data == null ? 0 : data.length;中会报错

将其更改为可为 null List? 可以解决此问题。

这是如何使用 FutureBuilder 进行操作的基本示例。它不调用 http 并使用有限的数据工作,仅模拟延迟,但您可以根据需要进行调整。您可以在 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'));
            }));
  }
}