Home > Blockchain >  LateInitializationError: Field has not been initialized
LateInitializationError: Field has not been initialized

Time:07-28

I am trying to start my main.dart file which is connected to an api. So far i found out that Late List<Cases> casesList is not nullable. I tried to do this List<Cases>? casesList when i do that i get a lot more errors. any help would be appriciated.

Error: LateInitializationError: Field 'casesList' has not been initialized.

Main.dart

class MyHomePage extends StatefulWidget {
  const MyHomePage({ Key? key, required this.title}) : super(key: key);


  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ApiService api = ApiService();
  late List<Cases> casesList;

  @override
  Widget build(BuildContext context) {
    if(casesList == null) {
      casesList = <Cases>[];
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: FutureBuilder(
            future: loadList(),
            builder: (context, snapshot) {
              return casesList.isNotEmpty? CasesList(cases: casesList):
              const Center(child:
              Text('No data found, tap plus button to add!')
              );
            },
          )
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _navigateToAddScreen(context);
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Future loadList() {
    Future<List<Cases>> futureCases = api.getCases();
    futureCases.then((casesList) {
      setState(() {
        this.casesList = casesList;
      });
    });
    return futureCases;
  }

Model.dart

class Cases {
  final int klantId;
  final String mailaddres;
  final String wachtwoord;
  final String klantvoornaam;
  final String tussenvoegsel;
  final String klantachternaam;
  final String bedrijfsnaam;
  final String telefoonnummer;

  Cases({ required this.klantId, required this.mailaddres, required this.wachtwoord, required this.klantvoornaam, required this.tussenvoegsel,
    required this.klantachternaam, required this.bedrijfsnaam, required this.telefoonnummer });

  factory Cases.fromJson(Map<String, dynamic> json) {
    return Cases(
      klantId: json['klantId'] as int,
      mailaddres: json['mailaddres'] as String,
      wachtwoord: json['wachtwoord'] as String,
      klantvoornaam: json['klantvoornaam'] as String,
      tussenvoegsel: json['tussenvoegsel'] as String,
      klantachternaam: json['klantachternaam'] as String,
      bedrijfsnaam: json['bedrijfsnaam'] as String,
      telefoonnummer: json['telefoonnummer'] as String,
    );
  }

  @override
  String toString() {
    return 'Trans{id: $klantId, name: $mailaddres, age: $wachtwoord}';
  }
}

caseslist.dart

class CasesList extends StatelessWidget {

  final List<Cases> cases;
  const CasesList({Key? key, required this.cases}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return
      ListView.builder(
          itemCount: cases == null ? 0 : cases.length,
          itemBuilder: (BuildContext context, int index) {
            return
              Card(
                  child: InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => DetailWidget(cases[index])),
                      );
                    },
                    child: ListTile(
                      leading: const Icon(Icons.person),
                      title: Text(cases[index].klantvoornaam),
                      subtitle: Text(cases[index].klantachternaam.toString()),
                    ),
                  )
              );
          });
  }
}

privider.dart

  Future<List<Cases>> getCases() async {
    Response res = await get(Uri.parse(apiUrl));

    if (res.statusCode == 200) {
      List<dynamic> body = jsonDecode(res.body);
      List<Cases> cases = body.map((dynamic item) => Cases.fromJson(item)).toList();
      return cases;
    } else {
      throw "Failed to load cases list";
    }
  }

CodePudding user response:

just add this method to your class

@override
void initState() {
  super.initState();
  casesList = [];
}

or initialize the list as below:

List<Cases> casesList = [];
  • Related