Emir
Emir

Reputation: 7

I can't use it without giving data to variables in dart classes

Code:

class Personel{    
  String ad;
  String soyad;
  int kidem;
  String durum;

  Personel(String ad, String soyad, int kidem){
    this.ad = ad;
    this.soyad = soyad;
    this.kidem = kidem;
    this.durum = durum;
  }
}

Error:

: Error: Field 'ad' should be initialized because its type 'String' doesn't allow null.
lib/personeller.dart:2
  String ad;
         ^^
: Error: Field 'soyad' should be initialized because its type 'String' doesn't allow null.
lib/personeller.dart:3
  String soyad;
         ^^^^^
: Error: Field 'kidem' should be initialized because its type 'int' doesn't allow null.
lib/personeller.dart:4
  int kidem;
      ^^^^^

What is the problem and how can I fix it? I am trying to use this code in flutter.

import 'package:flutter/material.dart';
import 'package:untitled1/personeller.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    List <Personel> personelListesi = [Personel("Levent", "Ertunalı", 13), Personel("Emir", "Bolat", 16), Personel("Ahmet", "Gaya", 21)];
  
  return Scaffold(
    appBar: AppBar(
      title: Text("Personel Listesi"),
    ),

    body: Column(
      children: <Widget>[
        Expanded(
          child: ListView.builder(
            itemCount: personelListesi.length,
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text(personelListesi[index].ad + " " + personelListesi[index].soyad),
                subtitle: Text("Kıdem yılı: " + personelListesi[index].kidem.toString()),
                trailing: Icon(Icons.done),
            );
          },
        ),
        ),
      ]
    )
  );
  }}

My goal is to enter information into the list with the methods determined in the class. I will reflect the information I entered in the form of a list, there is no problem in Flutter codes, but I get an error in Class codes.

Upvotes: 0

Views: 39

Answers (1)

S. M. JAHANGIR
S. M. JAHANGIR

Reputation: 5070

Change this:

class Personel{
  String ad;
  String soyad;
  int kidem;
  String durum;

  Personel(String ad, String soyad, int kidem){
   this.ad = ad;
   this.soyad = soyad;
   this.kidem = kidem;
   this.durum = durum;
 }
}

To this:

class Personel{
   String ad;
   String soyad;
   int kidem;
   String? durum;

   Personel(this.ad, this.soyad, this.kidem);
}

Upvotes: 1

Related Questions