Home > database >  How to access array inside array in flutter
How to access array inside array in flutter

Time:04-14

Here i got some list of array

 {
    "id": 1,
    "username": "dragonknight",
    "password": "123",
    "email": "[email protected]",
    "nama_lengkap": "Dragon Knight",
    "createdAt": "2022-04-13T05:50:00.559Z",
    "updatedAt": "2022-04-13T05:50:00.559Z",
    "grupId": 1,
    "grup": {
        "id": 1,
        "nama_grup": "fleetime",
        "deskripsi": "Ini deskripsi",
        "createdAt": "2022-04-13T05:53:18.423Z",
        "updatedAt": "2022-04-13T05:53:18.423Z"
    }
},

the problem is i want to enter grup array and enter nama_grup in flutter how do i do that. i tried with username and nama_lengkap and data show up correctly. but with grup it shows as null.

home.dart

https://pastebin.com/raw/F3Ha8vKK

CodePudding user response:

You need to separate grup from object then access it. Wait for shared instance loaded then find for user string, if found do the json decode. Here is the working example:

class _DashboardState extends State<Dashboard> {
  final Future<SharedPreferences> localStorage = SharedPreferences.getInstance();
  String nama_grup = '';

  @override
  void initState() async {
    super.initState();

    // wait for SharedPreferences instance
    final prefs = await localStorage;

    // find user string from SharedPreferences
    final String? user = prefs.getString('user');

    var userGrup = [];

    if (user != null) {
      // decode json string if found
      var userDecoded = json.decode(user);

      setState(() {
        userGrup.add(userDecoded['grup']);
        nama_grup = userGrup[0]['nama_grup'];
      });
    }
  }
  ...
  • Related