Home > Net >  How do I get data that is usually received with widget.[etc]?
How do I get data that is usually received with widget.[etc]?

Time:05-28

I'm trying to create an ExpansionPanel with data from a map. I have my data being created from an API in a separate function and am passing the data in with this.branchData. I've attached my code below:

class RunList extends StatefulWidget {

// Creates a list of packages.
final Map branchData;

// Defines what needs to be passed into the class. Needs the branchNames list.
RunList(this.branchData, {Key? key}) : super(key: key);
@override

// Creates mutable state for that widget at a given location in the tree.
// Returns _ProjectDropdownState() which extends the State.

State<RunList> createState() => _RunListState();
}

However, I'm trying to access branchData in a separate function called generateItems, but I get the error 'Undefined name 'branchData'.' I'm able to access branchData using widget.branchData, however, I can't use that in generateItems. Is there any way I can get branchData elsewhere in my code to be usable in generateItems? I've attached generateItems below:

List<Item> generateItems(int numberOfItems) {

  List<Item> runData = [];

  // Create Item
  var run = new Item (
    headerValue: branchData["refs/heads/main"][branchData["branchRuns"]["refs/heads/main"][0]].commitTitle,
    expandedValue: 'Nothing to see yet...',
  );
  runData.add(run);

  return runData;
}

CodePudding user response:

So you have data named branchData within class RunList.

Case1: If you're calling generateItems function within the build method of _RunListState():

While calling the function generateItems() pass the data from the widget using widget.branchData (this is instance of data from the parent widget, here RunList). Now you can await for result in case of async func, or continue your program.



Case2: calling generateItems function from another widget:

My approach would be to use provider implementation. While you get access to branchData on creation of RunList class, send the value to provider so that you can access it from anywhere in the widget tree. There are multiple tutorials on YT for this implementation.

CodePudding user response:

Instead of using an external function to create a list of widgets you can create them by using List.generate For example:

List.generate(branchData["refs/heads/main"][branchData["branchRuns"]]["refs/heads/main"].length, (index) { 
   return Item (
    headerValue: branchData["refs/heads/main"][branchData["branchRuns"]]["refs/heads/main"][index].commitTitle,
    expandedValue: 'Nothing to see yet...',
  );
});
  • Related