'how to show json object in a listview flutter

I have json file with the following data in it:

{
  "item1": "value1",
  "item2": "value2",
  "item3": "value3"
}

I also have Items() class 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 this stateful widget which i want to use to show the list of items

 class ItemsView extends StatefulWidget {
  const ItemsView({Key? key}) : super(key: key);

  @override
  _ItemsViewState createState() => _ItemsViewState();
}

class _ItemsViewState extends State<ItemsView> {
  late String items = "";
  setItems() async {
    final itemsList = Items().getItems().toString();
    setState(() {
      items = itemsList;
    });
  }

  @override
  initState() {
    setItems();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: ListView.builder(itemBuilder: itemBuilder),
      ),
    );
  }
}

I want to show the list of items from the json with a ListView.builder. I also want to add another item like "item4" with a key value in the json file and the ListView.builder should add the new item automaticly. I wonder how i can achieve this?

Edit

I also want to just update the json file if i want to add another item, so i avoid using a model because you also have to update the model if i want to add another item.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source