Search code examples
jsonflutterapiflutter-listview

How to access Json data's


I have some Json data. But i cannot access its inside without write first key name. Json data's link is https://api.genelpara.com/embed/borsa.json I want to put them to Listview. How can I put them? If I write like code , I can access only 'satis' key and value and display on Listview but I want to access 'ALGYO' key as a value and show on Listview.

child: Center(child: Text(' ${snapshot.data['ALGYO']['satis']}'))


Solution

  • You need to get the keys from your JSON (like ALGYO and ARZUM) and then you can access data inside. Try the following code, you can easily add alis and degisim where you want:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'ListView',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const HomePage(),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      const HomePage({Key? key}) : super(key: key);
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      final data = {
        'ALGYO': {'satis': "20.18", 'alis': "20.16", 'degisim': "-1,46"},
        'ARZUM': {'satis': "17.68", 'alis': "17.68", 'degisim': "-20,93"},
        'ACSEL': {'satis': "16.41", 'alis': "16.41", 'degisim': "-2,32"},
        'ADANA': {'satis': "12.19", 'alis': "12.19", 'degisim': "0,00"},
        'ADBGR': {'satis': "8.62", 'alis': "8.62", 'degisim': "0,00"},
        'ADEL': {'satis': "0.0476", 'alis': "0.0476", 'degisim': "-1,04"},
        'ADESE': {'satis': "1.2", 'alis': "1.2", 'degisim': "-1,64"},
        'ADNAC': {'satis': "2.09", 'alis': "2.09", 'degisim': "0,00"},
        'AEFES': {'satis': "21.46", 'alis': "21.46", 'degisim': "-1,29"},
        'AFYON': {'satis': "3.63", 'alis': "3.63", 'degisim': "-0,82"},
      };
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('ListView'),
          ),
          body: ListView.builder(
            itemCount: data.length,
            itemBuilder: (BuildContext context, int index) {
              // this will be the key for the current item
              String key = data.keys.elementAt(index);
              // here you can see how to access "satis" under
              // current key
              return ListTile(
                  title: Text("$key"), subtitle: Text(data[key]!["satis"]!));
            },
          ),
        );
      }
    }