Sachin Kosalia
Sachin Kosalia

Reputation: 43

Not able to add items to a list in flutter

I was trying to create a list such that i can access it anywhere.So i created a class and in that i created a empty list .But when i try to add item in that from outside through the function inside the class it doesnt get added.It prints like its added but it isnt .

import 'package:flutter/material.dart';
class PlaybackQueue{
  List<String > playbackQueue = <String>[];
 addToQueue(value)async{
     playbackQueue.add(value);
  //  playbackQueue.insert(0,"value"); // also tried this but this doesnt work too
 //print(value);
    print(playbackQueue.length);
    print(playbackQueue.first + "yih");
    print(PlaybackQueue().playbackQueue);
}
removeFirstElement(){
   playbackQueue.removeAt(0);
}
clearQueue(){
   playbackQueue.clear();
}
}

class PlaybackQueueView extends StatefulWidget {
 const  PlaybackQueueView({Key? key}) : super(key: key);

  @override
  State<PlaybackQueueView> createState() => _PlaybackQueueViewState();
}

class _PlaybackQueueViewState extends State<PlaybackQueueView> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title:const Text("PLAYBACK QUEUE"),),
      body: Container(color: Colors.white,
        child: Column(children: [
          if(PlaybackQueue().playbackQueue.isNotEmpty == true)
          for(int i = 0 ; i <  PlaybackQueue().playbackQueue.length ; i++ )
            Text(PlaybackQueue().playbackQueue.elementAt(i)),
          FloatingActionButton(onPressed: (){

               PlaybackQueue().addToQueue('value');
          },)
        ],),
      ),
    );
  }
}

here is my console

I/flutter ( 7546): 1
I/flutter ( 7546): valueyih
I/flutter ( 7546): []

Upvotes: 1

Views: 936

Answers (2)

FDuhen
FDuhen

Reputation: 4816

Whenever you're using PlaybackQueue(), a new instance of your object is created.

You can either instantiate your PlaybackQueue object in your initState method like so

 late PlaybackQueue playbackQueue;

  @override
  void initState() {
    super.initState();
    playbackQueue = PlaybackQueue();
  }

and then in your widget Tree, use the playbackQueue variable.

Another solution would be to use the GetIt package to register your PlaybackQueue as a Singleton and use a single instance across your whole app.
Consider using this solution if this model must be accessed from multiple widgets.

Example using GetIt :
1- Register your Singleton in your main.dart file

final GetIt getIt = GetIt.instance;

void main() {
  getIt.registerSingleton(PlaybackQueue());

  ...
  //Rest of your main() code
}

2- In your Widgets

late PlaybackQueue playbackQueue = getIt.get();

@override
  Widget build(BuildContext context) {
    ...
    playbackQueue.yourMethod();
    ...
  }

Upvotes: 1

Jaber Bin Ahamed
Jaber Bin Ahamed

Reputation: 41

Create a method inside setState() method , that will add the item.

Upvotes: 0

Related Questions