I have json file with the following data in it:
{
"item1": "value1",
"item2": "value2",
"item3": "value3"
}
I also have Items()
class in a seperate file which has the method getItems()
method which loads the json file:
class Items {
Future<Map<String, dynamic>> getItems() async {
String jsonData =
await rootBundle.loadString('assets/items.json');
Map<String, dynamic> data = jsonDecode(jsonData);
return data;
}
}
I also have a scaffold to show the items with ListView.builder
. I first use setState
to assign the returned value of Items().getItems()
to the field items
. I then use the value of the field inside the LisView.builder
class ItemList extends StatefulWidget {
const ItemList({Key? key}) : super(key: key);
@override
_ItemListState createState() => _ItemListState();
}
class _ItemListState extends State<ItemList> {
late String items = '';
setItems() async {
final item = await Items().getItems();
setState(() {
items = jsonEncode(item);
});
}
@override
initState() {
setItems();
}
@override
Widget build(BuildContext context) {
Map<String, dynamic> data = jsonDecode(items);
debugPrint(data.toString());
debugPrint(items);
return Scaffold(
body: ListView.builder(
itemCount: data.keys.length,
itemBuilder: (c, index) {
return ListTile(
title: Text("key " data.keys.toList()[index]),
subtitle: Text("value " data.values.toList()[index]),
);
},
),
);
}
}
I am able to show the list of items on the Scaffold()
but i still get the error: Unexpected end of input (at character 1)
When i click on the error it highlights on the jsonDecode(items)
. So something goes wrong there but i don't know what.
CodePudding user response:
Try to simplify your code like this
class _ItemListState extends State<ItemList> {
Map<String, dynamic> data = {};
setItems() async {
await Items().getItems().then((value) => setState(() => data = value));
}
@override
initState() {
setItems();
}
@override
Widget build(BuildContext context) {
debugPrint(data);
//rest of code ...
}
and check if you still get the error.