Flutter#2 : How can i achieve this in flutter?

Viewed 46

I want to print out a list of "item" by creating a listview inside my code

return Container(
  color: Palette.scienceBlue,
  child: Visibility(
    replacement: DevicePage(),
    visible: scanDeviceProvider.getVisible,
    child: Column(
      children: [
        const AppBarSideBarAndAddButton(),
        
        SizedBox(child: Container(
        // I need to print a list of "items" here
    )),
      ],
    ),
  ),
);
Future<void> onScan(dynamic data) async {
  var dataResponse = DataResponse.fromJson(data);
  print(dataResponse.toJson());
  List<dynamic> dt = jsonDecode(jsonEncode(dataResponse.data).toString());
  dt.forEach((element) {
    var item = Data.fromJson(element);

    print(item.model_Name);
  });
}

i tried with listview.buider but got quite a few errors. i have a function to get data from json file is onScan and i want to read item.model_Name in this function displayed on the screen how can i do it?

1 Answers

You should change onScan to return the list of Data.

Future<List<Data>> onScan(dynamic data) async {
  var dataResponse = DataResponse.fromJson(data);
  print(dataResponse.toJson());
  List<dynamic> dt = jsonDecode(jsonEncode(dataResponse.data).toString());
  return dt.map((element) => Data.fromJson(element)).toList();
}

With this you can use the FutureBuilder to display the data in your Listview.

FutureBuilder<List<Data>>(
  future: onScan(data),
  builder: (BuildContext context, AsyncSnapshot<List<Data>> snapshot){
     if (snapshot.hasData) {
       final List<Data> scannedData = snapshot.data;
       return ListView(...)
     } else {
       ...
     }
  }
)

You can then access your items with scannedData.

Related