Abdulrhman atta
Abdulrhman atta

Reputation: 11

LateInitializationError: Field 'trackList' has not been initialized

I want to read the list from the api I created but everytime I'm trying to get my list from the api but I keep recieving this error and I don't know why ? it seem like there is an error in this age but I can't figure where is the error , please if anyone can help I will be thankful.

I want to read the list from the api I created but everytime I'm trying to get my list from the api but I keep recieving this error and I don't know why ? it seem like there is an error in this age but I can't figure where is the error , please if anyone can help I will be thankful.

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
   


    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
   
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,

      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  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<Track> trackList;



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

    return Scaffold(
      backgroundColor: Color(0xff121219),
      appBar: AppBar(
        backgroundColor: Color(0xff121219),
        actions: [
           IconButton(
          icon: const Icon(Icons.music_note),
          tooltip: 'Increase volume by 10',
          onPressed: () {
              //  Navigator.push(context,
              //                         MaterialPageRoute(builder: (context) {
              //                       return TrackList( track: [],);
              //                     }));
          },
        ),
        ],
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Image(image: AssetImage('assets/logo.png'), fit: BoxFit.cover, width: 170,),
          ],
        ),

      ),
      body: Center(

      //   child: Column(
          
      //  mainAxisAlignment: MainAxisAlignment.center,
      //     children: <Widget>[
      //       Container(
      //         margin: EdgeInsets.only(bottom: 40),
      //         child: Image(image: AssetImage('assets/vinyl.png'), fit: BoxFit.cover, width: 170,)),
      //       SizedBox(height: 20),
      //       Text(
      //         'Please tab on the "+" to add tracks',
      //         style:TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize:14 ),
              
      //       ),
      //     ],
      //   )

   
        child: trackList.length > 0  ? Container(
        child: new Center(
            child: new FutureBuilder(
              future: loadList(),
              builder: (context, snapshot) {
                return trackList.length > 0? new TracksList(tracks: trackList):
                new Center(child:
                new Text('No data found, tap plus button to add!', style: Theme.of(context).textTheme.title));
              },
            )
        ),
      )  :  Column(
          
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: 40),
              child: Image(image: AssetImage('assets/vinyl.png'), fit: BoxFit.cover, width: 170,)),
            SizedBox(height: 20),
            Text(
              'Please tab on the "+" to add tracks',
              style:TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize:14 ),
              
            ),
          ],
        )
      ),
        
      
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color(0xffDE1534),
        onPressed: () {
                                  Navigator.push(context,
                                      MaterialPageRoute(builder: (context) {
                                    return AddDataWidget();
                                  }));
                                },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
  Future loadList() async {
    Future<List<Track>> futureCases =  api.getTracks();
    futureCases.then((trackList) {
      setState(() {
        this.trackList = trackList;
      });
    });
    return await futureCases;
  }
}


Upvotes: 1

Views: 74

Answers (2)

Chukwuebuka Amaechi
Chukwuebuka Amaechi

Reputation: 41

From your declaration, late List trackList says your list cannot be null so the null check in build method before the scaffold will return will always be false as trackList cannot be null(dart intellisense should have told you this) and an empty list is never assigned, so trackList is never initialized

Solution: declare your variable as List trackList = []; this way it's not empty or null by default, you can reassign it when your API call completes. Of course, remove the null check and assignment in the build method, it is pointless.

Your approach does defile the purpose of the future builder you're using. If you're checking the state of your future call yourself and calling setState, then no need using a futurebuilder which is built to automatically manage the state of futures

Upvotes: 1

Lai Zong Hao
Lai Zong Hao

Reputation: 46

Try to change your variable:

late List<Track> trackList; to

List<Track> trackList = [];

The error indicate your trackList is not initialise after build() is rendered

Upvotes: 0

Related Questions