0

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

5
  • could you clarify your question it's quite hard to under stand? provide what's happening and what you want Commented Apr 14, 2022 at 3:47
  • I want to show group name dynamically from an API. and i want to show it in Flutter frontend. tthe problem is when i access an array within an array i got null. Commented Apr 14, 2022 at 3:50
  • My home.dart dashboard when i access normal array nama_lengkap and it does works. but when i tried nama_grup it shows as null pastebin.com/raw/F3Ha8vKK Commented Apr 14, 2022 at 3:53
  • did you access it like object['grup']['nama_grup']? Commented Apr 14, 2022 at 3:55
  • yup done that still got null Commented Apr 14, 2022 at 3:56

1 Answer 1

1

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'];
      });
    }
  }
  ...
Sign up to request clarification or add additional context in comments.

3 Comments

It says the method [] was called on null imgur.com/96vAWtd
You might need do json decode after finding user String see updated code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.