简体   繁体   中英

How to add API json response to Swipeable Cards Flutter - https://pub.dev/packages/swipeable_card_stack

I need to show list of profiles on Swipe cards in Flutter. I have used https://pub.dev/packages/swipeable_card_stack flutter library to display the profile cards. When I add static data, multiple cards are shown as expected. But when I am passing my JSON list it is not displaying any card, but only first or any other hardcoded card item number when passed is displayed as single card. Below is what I have done till now

class Dashboard extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return DashboardStateHolder();
  }
}

class DashboardStateHolder extends State<Dashboard> {
  int counter = 20;

  late QuadCardsResponse quadCardsResponseNew;
  late SharedPreferences sharedPreferences;
  late String? id = "",
      name = "",
      email = "",
      mobNum = "",
      colgName = "",
      colgShort = "",
      primaryColor = "",
      secondaryColor = "",
      accessToken = "",
      latitude = "",
      longitude = "";

  int cardsLength = 0;

  // List<QuadCardsResponse> items = <QuadCardsResponse>[];

  // List<Widget> cardItems = <Widget>[];

  var nameList = <CardView>[];

  List<CardView> cardItems = <CardView>[];
  var items = <CardView>[];
  SwipeableCardSectionController _cardController =
  SwipeableCardSectionController();

  @override
  void initState() {
    super.initState();
    getRequiredData();
  }

  Future<void> getRequiredData() async {
    sharedPreferences = await SharedPreferences.getInstance();
    print(sharedPreferences.getString("id"));
    print(sharedPreferences.getString("name"));
    print(sharedPreferences.getString("email"));
    print(sharedPreferences.getString("mobile_number"));

    print(sharedPreferences.getString("college_name"));
    print(sharedPreferences.getString("college_primary_color"));
    print(sharedPreferences.getString("college_secondary_color"));
    print(sharedPreferences.getString("api_access_token"));

    id = sharedPreferences.getString("id");
    name = sharedPreferences.getString("name");
    email = sharedPreferences.getString("email");
    mobNum = sharedPreferences.getString("mobile_number");
    colgName = sharedPreferences.getString("college_name");
    primaryColor = sharedPreferences.getString("college_primary_color");
    secondaryColor = sharedPreferences.getString("college_secondary_color");
    accessToken = sharedPreferences.getString("api_access_token");

    final List l =
        sharedPreferences.getString("college_name").toString().split(' ');
    print(l.length);
    int length = l.length;
    latitude = sharedPreferences.getString("lat");
    longitude = sharedPreferences.getString("long");
    print("lat");
    print(latitude);
    print("long");
    print(longitude);

    /// call API here to get swipe cards of students
    getSwipeCardsWS();
  }

  getSwipeCardsWS() async {
    DesignConstants.showLoaderDialog(context, "Hold on ... !");

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    Response response;
    final Dio dio = Dio();
    dio.options.headers['content-Type'] = 'application/json';
    dio.options.headers["Authorization"] =
        "${sharedPreferences.getString('api_access_token')}";
    response = await dio.post(apiConfig.getSwipeCards, queryParameters: {
      'latitude': sharedPreferences.getString("lat"),
      'longitude': sharedPreferences.getString("long"),
    });
    print(response.data.toString());

    if (response.data['status'] == "success") {
      print("cards-length");
      print(response.data['data'].length);
      cardsLength = response.data['data'].length;
      Navigator.pop(context);
      // quadCardsResponse = quadCardsResponseFromJson(response.toString());
      quadCardsResponseNew = quadCardsResponseFromJson(response.toString());
      print("data-coming-here-now");
      print(quadCardsResponseNew.data.toString());

      /*cardItems.add(quadCardsResponseNew);
      print("items-length");*/

      quadCardsResponseNew.data.forEach((element) {
        cardItems.add(CardView(element.name, element.profileImages[0]));
        _cardController.addItem(CardView(element.name, element.profileImages[0]));
      });

      print("_________LENGTH_________");
      print(cardItems.length);
      print(cardItems.toString());
      //

      for (var i = 0; i < cardItems.length; i++) {
        items.add(cardItems[i]);
      }
      print("for-loop-items");
      print(items.length);
    } else {
      Navigator.pop(context);
      print('Error in API response');
    }

    return quadCardsResponseNew.data;
  }

  @override
  Widget build(BuildContext context) {
    //create a CardController

    return WillPopScope(
      onWillPop: () {
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => QuadHome()));
        return Future.value(false);
      },
      child: Scaffold(
        backgroundColor: ColorConstant.otherWhiteShade,
        floatingActionButton: Padding(
            padding: EdgeInsets.fromLTRB(0, 0, 0, 30),
            child: MaterialButton(
              child: Padding(
                padding: EdgeInsets.all(20),
                child: Text(
                  "quad",
                  style: TextStyle(
                    fontSize: 18.0,
                    fontFamily: 'comfortaa',
                    fontWeight: FontWeight.bold,
                    letterSpacing: 00,
                    color: ColorConstant.quadTextSwipeCard,
                  ),
                ),
              ),
              onPressed: () {
                print("name-card");
                for (var i = 0; i < cardItems.length; i++) {
                  items.add(cardItems[i]);
                }
              },
              color: Colors.white,
              textColor: Colors.deepPurpleAccent,
              padding: EdgeInsets.all(16),
              shape: CircleBorder(
                  side: BorderSide(
                      color: ColorConstant.quadFloatingButtonColorShoadow
                          .withOpacity(0.3),
                      width: 3,
                      style: BorderStyle.solid)),
            )),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        body: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Center(
              child: Padding(
                padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
                child: Image.asset(
                  'images/quadheadbar.png',
                  height: 100,
                  width: 250,
                ),
              ),
            ),
            SwipeableCardsSection(
              cardController: _cardController,
              context: context,
              items: /*[CardView(cardItems.first.name, cardItems.first.profileImage),],*/
                // CardView(cardItems.first.name, cardItems.first.profileImage),
              cardItems.map((e) => CardView(e.name, e.profileImage)).toList(),

              // [cardItems.first, cardItems.last], items
              onCardSwiped: (dir, index, widget) {
                //Ad d the next card
                // print("*******On*"+)
                // quadCardsResponseNew.data.forEach((element) {
                //
                // });

                // if (counter <= quadCardsResponseNew.data.length) {
                //   _cardController.addItem(CardView(""));
                //   counter++;
                // }

                /*if (dir == Direction.left) {
                  print('onDisliked ${(widget as CardView)} $index');
                } else if (dir == Direction.right) {
                  print('onLiked ${(widget as CardView)} $index');
                } else if (dir == Direction.up) {
                  print('onUp ${(widget as CardView)} $index');
                } else if (dir == Direction.down) {
                  print('onDown ${(widget as CardView)} $index');
                }*/
              },
              enableSwipeUp: true,
              enableSwipeDown: true,
              /*cardHeightBottomMul: 0.0,
            cardHeightMiddleMul: 0.0,*/
            ),
            Container(
              margin: const EdgeInsets.symmetric(vertical: 20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Padding(
                      padding: const EdgeInsets.fromLTRB(30, 0, 0, 0),
                      child: MaterialButton(
                        onPressed: () {},
                        color: ColorConstant.cancelOptionSwipeCard,
                        textColor: Colors.white,
                        child: Icon(
                          CupertinoIcons.clear,
                          size: 48,
                        ),
                        padding: EdgeInsets.all(16),
                        shape: CircleBorder(),
                      )),
                  Padding(
                      padding: const EdgeInsets.fromLTRB(0, 0, 30, 0),
                      child: MaterialButton(
                        onPressed: () {},
                        color: ColorConstant.likeOptionSwipeCard,
                        textColor: Colors.white,
                        child: Icon(
                          CupertinoIcons.heart_fill,
                          size: 48,
                        ),
                        padding: EdgeInsets.all(16),
                        shape: CircleBorder(),
                      ))
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
class CardView extends StatefulWidget {

  String name, profileImage;

  CardView(this.name, this.profileImage);
  /*final List<QuadCardsResponse> list;

  const CardView(
      {Key? key, required this.list})
      : super(key: key);*/

  @override
  State<CardView> createState() => _CardViewState(name, profileImage);
}

class _CardViewState extends State<CardView> {
  String displayname, profileImage;

  _CardViewState(this.displayname, this.profileImage);

  TextEditingController graduationYearController = TextEditingController();
  String _chosenValue = '';
  int selectedValue = 0;
  late List<dynamic> streamList = [];
  List<String> streamData = <String>[];

  late QuadCardsResponse quadCardsResponse;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("profile-image");
    print(profileImage);
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(50),
      ),
      child: Stack(
        children: <Widget>[
          profileImage != '' ?
          Container(
            foregroundDecoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(50)),
              image: DecorationImage(
                  image: NetworkImage(
                      ""+profileImage),
                  fit: BoxFit.cover),
            ),
          ) : Container(
            height: 200,
            child: Image.asset(
              'images/quad_placeholder.png',
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              height: 250,
              width: double.infinity,
              foregroundDecoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(50)),
                gradient: LinearGradient(
                  end: const Alignment(0.0, -1),
                  begin: const Alignment(0.0, 0.4),
                  colors: <Color>[
                    const Color(0x8A000000),
                    ColorConstant.quadTextSwipeCard.withOpacity(0.0)
                  ],
                ),
              ),
            ),
          ),
          Align(
            alignment: Alignment.topCenter,
            child: Container(
                padding: const EdgeInsets.symmetric(
                    vertical: 16.0, horizontal: 16.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: const <Widget>[
                    Text(
                      "SDSU",
                      textAlign: TextAlign.start,
                      style: TextStyle(
                          color: Colors.white,
                          fontFamily: 'comfortaa',
                          fontWeight: FontWeight.w900,
                          letterSpacing: 2),
                    ),
                  ],
                )),
          ),
          Row(
            children: const [
              Align(
                alignment: Alignment.bottomLeft,
                child: Padding(
                  padding: EdgeInsets.fromLTRB(20, 00, 00, 60),
                  child: Chip(
                    backgroundColor: ColorConstant.chipColor,
                    label: Text('Business',
                      style: TextStyle(
                          color: ColorConstant.otherWhiteShade,
                          fontSize: 14.0,
                          fontFamily: 'comfortaa'),
                    ),
                  ),
                ),
              ),
              Align(
                alignment: Alignment.bottomLeft,
                child: Padding(
                  padding: EdgeInsets.fromLTRB(20, 00, 00, 60),
                  child: Chip(
                    backgroundColor: ColorConstant.chipColor,
                    label: Text('2024',
                        style: TextStyle(
                            color: ColorConstant.otherWhiteShade,
                            fontSize: 14.0,
                            fontFamily: 'comfortaa')
                    ),
                  ),
                ),
              ),
            ],
          ),
          Align(
            alignment: Alignment.bottomLeft,
            child: Container(
              padding:
              const EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.start,
                children:  <Widget>[
                  Padding(
                    padding: const EdgeInsets.fromLTRB(00, 00, 00, 100),
                    child: Text(""+displayname,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 40.0,
                          fontFamily: 'comfortaa',
                          fontWeight: FontWeight.w900),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

I am not sure what I am missing here or doing something in a wrong way.

cardItems is list of cardView so you don't need to do any thing just use it like this:

items: cardItems;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM