Home > Software design >  how to show json object in a listview flutter
how to show json object in a listview flutter

Time:03-09

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.

CodePudding user response:

you can try this

 class Items {
      Map<String, dynamic> getItems() {
        String jsonData = '{ "item1": "value1","item2": "value2","item3": "value3"}';
    
        Map<String, dynamic> data = jsonDecode(jsonData);
        return data;
      }
    }
    class App extends StatefulWidget {
      const Deneme({ Key key }) : super(key: key);
    
      @override
      _AppState createState() => _AppState();
    }
    
    class _AppState extends State<App> {
       
      @override
      Widget build(BuildContext context) {
        Map<String, dynamic> data =Items().getItems();
        return Scaffold(
            body: ListView.builder(
              itemCount: data.keys.length,
              itemBuilder: (c,index){
                return  ListTile(
                      
                        title: Text("Value " data.values.toList()[index]),
                        subtitle: Text("Key " data.keys.toList()[index]),
                        
                      );
              },
            ),
        );
      }
    }
  • Related