I have logged in from a api. Now i need to show the response of json data in a listview.builder. How can i do it?

I have looged in from a Api then got this response. I can fetch the data of id, name etc and also the unread_notification -> id , type etc in a listview.builder . But can not fetch the data of unread_notification " data" which has payment_id, amount etc. I need to fetch it too in a listview.builder . Can anyone help me with his knowledge. Check my all code which i am trying.

 {
    "id": 1,
    "name": "Mr Admin",
    "email": "admin2@gmail.com",
    "username": "admin2",
    "api_token": "oYfajebhRzlxpMZV8dHI6w5R8CrpgybaGqX2ZaIXkGpumE9hZSgLVVINAgaF",
    "user_types_id": null,
    "created_at": "2020-01-21 16:21:48",
    "updated_at": "2020-10-14 11:31:10",
    "deleted_at": null,
    "unread_notifications": [
        {
            "id": "d54ee0cc-054a-4d51-a53b-5f6f658841ae",
            "type": "App\\Notifications\\HandSlipStatusNotification",
            "notifiable_id": 1,
            "notifiable_type": "App\\User",
            "data": {
                "payment_id": 471,
                "generate_payment_id": "10200471",
                "message": "Hand Slip Settled.",
                "amount": 850
            },
            "read_at": null,
            "created_at": "2020-10-12 15:50:38",
            "updated_at": "2020-10-12 15:50:38"
        },
        {
            "id": "aedb7880-4201-4805-b017-62242dfed741",
            "type": "App\\Notifications\\HandSlipStatusNotification",
            "notifiable_id": 1,
            "notifiable_type": "App\\User",
            "data": {
                "payment_id": 471,
                "generate_payment_id": "10200471",
                "message": "Hand Slip Disbursed.",
                "amount": 850
            },
            "read_at": null,
            "created_at": "2020-10-12 15:50:25",
            "updated_at": "2020-10-12 15:50:25"
        },

login.dart

 import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import '../sharePreference.dart';
import 'homepage.dart';


class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
var data ;
var notification ;
  bool isprocesscomplete = false;
  TextEditingController _userController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  String BaseUrl = "my url";


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: SingleChildScrollView(
        child: Center(
          child: Container(
            padding: EdgeInsets.fromLTRB(20, 100, 20, 20),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  "Login",
                  style: TextStyle(fontSize: 32),
                ),
                SizedBox(
                  height: 30,
                ),
                Card(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Container(
                    height: 220,
                    width: MediaQuery.of(context).size.width,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Column(
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(30),
                          child: TextField(
                            controller: _userController,
                            decoration: InputDecoration(hintText: "username"),
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.all(30),
                          child: TextField(
                            controller: _passwordController,
                            obscureText: true,
                            decoration: InputDecoration(hintText: "Password"),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 60,
                  width: MediaQuery.of(context).size.width,
                  child: RaisedButton(
                    color: Colors.lightBlue,
                    onPressed: () {
                      if (_userController.text == "" ||
                          _passwordController.text == "") {
                        final snackBar = SnackBar(
                            content: Text("Enter Username and Password"));
                        _scaffoldKey.currentState.showSnackBar(snackBar);
                      } else {
                        signIn(_userController.text, _passwordController.text);
                      }
                    },
                    child: ProgressButton(),
                    shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(16),
                    ),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                FlatButton(
                  child: Text("Forgot password"),
                  onPressed: () {},
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget ProgressButton() {
    if (isprocesscomplete != false) {
      return CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white));
    } else {
      return new Text(
        "Sign In",
        style: const TextStyle(
          color: Colors.white,
          fontSize: 15.0,
        ),
      );
    }
  }

  void signIn(String username, String password) async {
    setState(() {
      isprocesscomplete = true;
    });
    var response = await http.post(BaseUrl,
        headers: {"Content-Type": "application/json"},
        body: json.encode({
          "username": username,
          "password": password,
        }));

    Map<String, dynamic> value = json.decode(response.body);
    // print('Respone ${response.body}');
    if (response.statusCode == 200) {
      try {
        ///You don't need it but it will be cool for show progress dialgo for 4 second then redirect even if we get reslut
        Future.delayed(Duration(seconds: 4), () {
          // 5s over make it false
          setState(() {
            isprocesscomplete = false;
          });
        });

        Map<String, dynamic> value = json.decode(response.body);
        notification = value ["unread_notifications"];

        print('Respone ${response.body}');
        SharedPrefrence().setToken(value['api_token'].toString());
        SharedPrefrence().setName(value['name']);
        SharedPrefrence().setUserId(value['id'].toString());

        ///This is used when user loged in you can set this true,
        ///next time you open you need to check loginc in main.dart or splashscreen if this is true if it is true then
        ///redirect to home page it is false then redirect to Login page
        ///When you logout the app make sure you set this as false like "SharedPrefrence().setLoggedIn(false);"
        SharedPrefrence().setLoggedIn(true);

        ///Redirect to Home page
        Navigator.pushAndRemoveUntil(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => HomePage(
                                      email: value['email'],
                                      notification: notification,

                                    )),
                                ModalRoute.withName("/login"));

      } catch (e) {
        e.toString();
        final snackBar =
        SnackBar(content: Text("something wrong,Try again 😑"));
        _scaffoldKey.currentState.showSnackBar(snackBar);
      }
    } else {
      var message = value['error'];
      final snackBar = SnackBar( backgroundColor: Colors.redAccent[700],
          content: Text(message.toString()));
      _scaffoldKey.currentState.showSnackBar(snackBar);
    }
  }
}

homepage.dart

 import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import '../sharePreference.dart';
    import 'login.dart';
    import 'login.dart';
    
    class HomePage extends StatefulWidget {
    
      String email;
      String name;
      String username;
      List notification ;
      List data ;
      HomePage({this.email, this.name, this.username,  this.notification, this.data});
    
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    
    
    class _HomePageState extends State<HomePage> {
    
      String nametoprint;
      String tokentoprint;
    
      @override
      void initState() {
        super.initState();
        Future name = SharedPrefrence().getName();
        name.then((data) async {
          nametoprint = data;
          print(nametoprint);
        });
    
        Future token= SharedPrefrence().getToken();
        token.then((data) async {
          tokentoprint= data;
          print(tokentoprint);
        });
      }
    
    
    
      int counter = 0;
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text("Cash-Management"),
              backgroundColor: Colors.blue,
              actions: [
    
                new Stack(
                  children: <Widget>[
                    new IconButton(icon: Icon(Icons.notifications), onPressed: () {
                      setState(() {
                        counter = 0;
                      });
                    }),
                    counter != 0 ? new Positioned(
                      right: 11,
                      top: 11,
                      child: new Container(
                        padding: EdgeInsets.all(2),
                        decoration: new BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(6),
                        ),
                        constraints: BoxConstraints(
                          minWidth: 14,
                          minHeight: 14,
                        ),
                        child: Text(
                          '$counter',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 8,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ) : new Container()
                  ],
                ),
                IconButton(
                    icon: Icon(Icons.exit_to_app),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => Login()),
                      );
                    }),
              ],
            ),
            body: ListView(
              children: <Widget>[
                Container(
                  height: 200,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      Text(
                        "  ${widget.email} ",
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(" ${nametoprint} "),
                      Text("$nametoprint"),
                      Text("$tokentoprint"),
                    ],
                  ),
                ),
    
    Container(
      color: Colors.blue,
      height: 300,
      child:   ListView.builder(
          itemCount: widget.notification == null ?  0 : widget.notification.length,
          itemBuilder: (context, index){
            return ListTile(
              title: Text(widget.notification[index] ["id"]),
              subtitle: Text(widget.notification[index]["type"]),
    
            );
          }),
    ),
    
    
    
              ],
            ),
    
            floatingActionButton: FloatingActionButton(onPressed: () {
              print("Increment Counter");
              setState(() {
                counter++;
              });
            }, child: Icon(Icons.add),),
          ),
        );
      }
    }

sharedpreferens.dart

import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

class SharedPrefrence {
  Future<bool> setToken(String token) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("token", token);
  }

  Future<String> getToken() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("token") ?? '';
  }

  Future<bool> setUserId(String userId) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("user_id", userId);
  }

  Future<String> getUserId() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("user_id") ?? '';
  }

  Future<bool> setName(String name) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("name", name);
  }

  Future<String> getName() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("name") ?? '';
  }

  Future<bool> setLoggedIn(bool status) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setBool("logged_in", status);
  }

  Future<bool> getLogedIn() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool("logged_in") ?? false;
  }
}

I need to show this array in my homepage in a listview.builder. Please help me.

"data": {
                    "payment_id": 471,
                    "generate_payment_id": "10200471",
                    "message": "Hand Slip Settled.",
                    "amount": 850
                },


Read more here: https://stackoverflow.com/questions/64399078/i-have-logged-in-from-a-api-now-i-need-to-show-the-response-of-json-data-in-a-l

Content Attribution

This content was originally published by Mir Fahim Rahman at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: