'Removing button and load data
Hey guys I need help with removing this button and load data from json file without need to click on that button Here's code
List _items = [];
// Fetch content from the json file
@override Widget build(BuildContext context) { Future readJson() async { final String response = await rootBundle.loadString('assets/aaaa.json'); final data = await json.decode(response); setState(() { _items = data['first']; }); }
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
ElevatedButton(
child: const Text('Load Data'),
onPressed: readJson,
),
// Display the data loaded from sample.json
_items.isNotEmpty
? Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_items[index]["aaaaa"]),
title: Text(_items[index]["aaaaa"]),
subtitle: Text(_items[index]["aaaaaa"]),
),
);
},
),
)
: Container()
],
),
),
);
}
Solution 1:[1]
You should check out Future Builder. There are some good examples on that page of how to use the widget, including how to show different widgets depending on if the data was loaded, is in the process of loading, or there was an error. readJson
would be the future in your case.
Solution 2:[2]
Call initState() before build function
@overrride
initState() {
readJson();
super.initState();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cvanbeek |
Solution 2 | Mostafa Mahmoud |