Home > Software engineering >  How to use a variable value outside a Future function in Flutter?
How to use a variable value outside a Future function in Flutter?

Time:11-16

I want to access the 'items' to use inside the widget to generate a List of items. How should I do it? I am new to flutter.

  Future<Breakfast> loadBreakfast() async {
    String jsonAddress = await _loadloadBreakfastAsset();
    Map<String,dynamic> map = json.decode(jsonAddress);
    List<dynamic> items = map["items"]; // I want to access it so that I can use it

    // This return value is thrown away, but this line is necessary to 
    // resolve the Future call that FutureBuilder is waiting on.
    return Future<Breakfast>.value();
  }

CodePudding user response:

You'll need a FutureBuilder to get the value and build a list containing data just make some changes to your Future function

Future<List> loadBreakfast() async {
    String jsonAddress = await _loadloadBreakfastAsset();
    Map<String, dynamic> map = json.decode(jsonAddress);
    List<dynamic> items = map["items"]; 
   
    return items;
  }

and use FutureBuilder Now

FutureBuilder(
        future: loadBreakfast(),
        builder: (context, AsyncSnapshot<List> snapshot) => ListView.builder(
            itemCount: snapshot.data!.length,
            itemBuilder: (context, index) => Text("${snapshot.data![index]}")));

CodePudding user response:

You are using Future<Breakfast> where it is returning List<Breakfast>.

If you wish to return, List<Breakfast> items then change method return type to

Future<List<Breakfast>> loadBreakfast() async{..}.

If your map["items"] is just single Breakfast, then replace List<dynamic> items with final items and return it.

CodePudding user response:

You will need to declare a global list variable;

List? global_list;

Change your method from Future<Breakfast> to Future<List<Breakfast>> Then, after declaring your list of received items.

List<dynamic> items = map['items'];

You use set state to assign this result to the global_list variable.

setState(({
items = global_list;
    }));

Your function then returns items

Then in your widget code, you use the map() method to access each item drawing an item for each. That is..

global_list.map((item){
       //return widget
        return Text(item.name);
      });

This will return a list of your items.

  • Related