I have a StatefulWidget
post_view that creates a DataTable
. The data used to fill up the DataTable
is from a static method in another class named Post:
`
static generateData(){
List<Post> postList= [];
postList.add(Post(title: "Coolest Post", numDownVotes: 6, numUpVotes: 9));
postList.add(Post(title: "Covid-19 vaccine found!", numDownVotes: 3, numUpVotes: 67));
postList.add(Post(title: "Unreal ending to basketball game", numDownVotes: 2, numUpVotes: 23));
postList.add(Post(title: "Sample Post", numDownVotes: 2, numUpVotes: 6));
postList.add(Post(title: "What A Save!", numDownVotes: 5, numUpVotes: 34));
return postList;
}
`
I have the DataCells
in the table such that the number of up/down votes are in a row widget within the data cell along with an icon button to change or increase/decrease the number of up/down votes respectively. So, I have a variable '_posts' declared inside post_view that calls generateData()
and displays the data, but I want to be able to manipulate this data and pass it to another widget BarGraph
, which will generate a bar chart of the dynamic data.
Here's my BarGraph
widget:
`
class BarGraph extends StatefulWidget {
BarGraph({Key? key, required this.tableData}) : super(key: key);
List<Post>? tableData;
@override
State<BarGraph> createState() => _BarGraphState();
}
`
The issue here is that TabelData
is not accessible at all but I want to be able to get the titles, numupvotes, and numdownvotes to be able to display them in a chart. I tried using a getter but the null check operator doesn't work with that. I'm completely stuck, any help would be appreciated!
CodePudding user response:
What about using any state management approaches such as: Bloc, Provider, etc. Using these libraries can solve your problem as well as make your code more organized. For example, using bloc will look like
class ManagePost extends Cubit<List<Post>> {
List<Post> postList = [];
void addPost(Post post) {
postList.add(Post);
emit(postList);
}
void deletePost() {}
void updateVote() {}
void getAllPost() {}
}
Next, wrap your view in BlocBuilder, it will listen to state of post list and update UI.
CodePudding user response:
Found the answer! Using widget.tableData I was able to access the data passed into that variable.
CodePudding user response:
You can either lift your state up or use a state management package
Reference
State Management Package