Home > Software design >  I fetch the details of the model using flutter http
I fetch the details of the model using flutter http

Time:11-07

I am trying to show the details of the model just like we press one product then we can see the details of that product. Just like that I want to you show my model.

Here is the model:

class DisplayModel {
  String? status;
  List<Results>? results;

  DisplayModel({this.status, this.results});

  DisplayModel.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    if (json['results'] != null) {
      results = <Results>[];
      json['results'].forEach((v) {
        results!.add(new Results.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    if (this.results != null) {
      data['results'] = this.results!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Results {
  int? id;
  List<Products>? products;
  List<Catalogs>? catalogs;
  String? name;
  Null? description;
  String? category;
  String? templateName;
  Null? bannerText;

  Results(
      {this.id,
      this.products,
      this.catalogs,
      this.name,
      this.description,
      this.category,
      this.templateName,
      this.bannerText});

  Results.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    if (json['products'] != null) {
      products = <Products>[];
      json['products'].forEach((v) {
        products!.add(new Products.fromJson(v));
      });
    }
    if (json['catalogs'] != null) {
      catalogs = <Catalogs>[];
      json['catalogs'].forEach((v) {
        catalogs!.add(new Catalogs.fromJson(v));
      });
    }
    name = json['name'];
    description = json['description'];
    category = json['category'];
    templateName = json['template_name'];
    bannerText = json['banner_text'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    if (this.products != null) {
      data['products'] = this.products!.map((v) => v.toJson()).toList();
    }
    if (this.catalogs != null) {
      data['catalogs'] = this.catalogs!.map((v) => v.toJson()).toList();
    }
    data['name'] = this.name;
    data['description'] = this.description;
    data['category'] = this.category;
    data['template_name'] = this.templateName;
    data['banner_text'] = this.bannerText;
    return data;
  }
}

class Products {
  int? id;
  String? name;
  Null? unit;
  String? price;
  Null? salePrice;
  String? image;
  Null? category;
  Null? badge;

  Products(
      {this.id,
      this.name,
      this.unit,
      this.price,
      this.salePrice,
      this.image,
      this.category,
      this.badge});

  Products.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    unit = json['unit'];
    price = json['price'];
    salePrice = json['sale_price'];
    image = json['image'];
    category = json['category'];
    badge = json['badge'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['unit'] = this.unit;
    data['price'] = this.price;
    data['sale_price'] = this.salePrice;
    data['image'] = this.image;
    data['category'] = this.category;
    data['badge'] = this.badge;
    return data;
  }
}

class Catalogs {
  int? id;
  Null? name;
  Null? unit;
  Null? price;
  Null? salePrice;
  String? image;
  Null? video;
  Null? badge;

  Catalogs(
      {this.id,
      this.name,
      this.unit,
      this.price,
      this.salePrice,
      this.image,
      this.video,
      this.badge});

  Catalogs.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    unit = json['unit'];
    price = json['price'];
    salePrice = json['sale_price'];
    image = json['image'];
    video = json['video'];
    badge = json['badge'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['unit'] = this.unit;
    data['price'] = this.price;
    data['sale_price'] = this.salePrice;
    data['image'] = this.image;
    data['video'] = this.video;
    data['badge'] = this.badge;
    return data;
  }
}

Here is my controller:

List<DisplayModel> _displays = [];

  Future<bool> getDisplays() async {
    var url = Uri.parse(
        "https://digital-display.betafore.com/api/v1/digital-display/displays/");
    var token = localStorage.getItem('access');

    try {
      http.Response response = await http.get(url, headers: {
        "Authorization":
            "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjY3NzYwOTY1LCJpYXQiOjE2Njc2NzQ1NjUsImp0aSI6ImE1ZjAyOTJlYTE1MjRhNDM5YzI2YWYwZGQzNjA3YjZlIiwiaWQiOjV9.yjKKzalzRvSrSiSBUhZtZVg3wBy_o7P2Wvy7sbMOOT0"
      });
      // var data = json.decode(response.body) as List;

      // List<DisplayModel> temp = [];
      // for (var element in data) {
      //   DisplayModel displayModel = DisplayModel.fromJson(data);
      //   temp.add(displayModel);
      // }
      var data = json.decode(response.body);

      List<DisplayModel> temp = [];

      DisplayModel displayModel = DisplayModel.fromJson(data);
      temp.add(displayModel);
      print("length = ${temp[0].results?.length}");

      _displays = temp;
      notifyListeners();
      return true;
    } catch (exception) {
      log(exception.toString());
      return false;
    }
  }

  List<DisplayModel> get displays {
    return [..._displays];
  }

  DisplayModel singleDisplay(int id) {
    return _displays.firstWhere((element) => element.results);
  }

I tried to fetch like this:

DisplayModel singleDisplay(int id) {
    return _displays.firstWhere((element) => element.results![0].id == id);
  }

But I am getting only the first one not the others. Can you please tell me how can i Do this?

Here is the frontend where I want to shwo the details:

import 'package:digitaldisplay/controllers/DisplayController.dart';
import 'package:digitaldisplay/models/DisplayModel.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ShowDisplay extends StatelessWidget {
  static const routeName = "/show-display";

  const ShowDisplay({super.key});

  @override
  Widget build(BuildContext context) {
    final displayId = ModalRoute.of(context)!.settings.arguments;
    final display =
        Provider.of<DisplayController>(context).singleDisplay(displayId as int);
    return Scaffold(
      appBar: AppBar(),
      body: Container(child: Text(display.results![0].name as String)),
    );
  }
}

Here is the code of how I am redirecting to showdisplay page:

import 'package:digitaldisplay/views/screens/ShowDisplay.dart';
import 'package:flutter/material.dart';
import 'package:responsive_toolkit/responsive_toolkit.dart';

class DisplayCard extends StatelessWidget {
  final int id;
  final String displayName;
  final String displayImage;
  // final String location;
  // final String displayStyle;
  // final String displayImage;

  DisplayCard(
      {required this.displayName,
      required this.displayImage,
      required this.id});

  // const DisplayCard({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final ButtonStyle buttonStyle1 = ElevatedButton.styleFrom(
      backgroundColor: Colors.black,
      shape: const StadiumBorder(),
    );

    final ButtonStyle buttonStyle2 = ElevatedButton.styleFrom(
      backgroundColor: Color(0xFFc3232a),
      shape: const StadiumBorder(),
    );

    return InkWell(
      onTap: () {
        Navigator.of(context).pushNamed(ShowDisplay.routeName, arguments: id);
      },
      child: Container(
        margin: const EdgeInsets.all(10.0),
        alignment: Alignment.center,
        height: 300.0,
        width: double.infinity,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: const [
              BoxShadow(
                color: Color(0xFFffffff),
                //offset: Offset(2, 2),
                blurRadius: 0.5,
                spreadRadius: 1.0,
              ),
            ]),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          //mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: 55.0,
                  width: 120.0,
                  //color: Colors.black,
                  child: const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Card(
                      //margin: EdgeInsets.all(10.0),
                      color: Colors.black,
                      elevation: 10.0,
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Text(
                          "Dhanmondi",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 12.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                Container(
                  height: 55.0,
                  width: 120.0,
                  //color: Colors.black,
                  child: Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Card(
                      //margin: EdgeInsets.all(10.0),
                      color: Colors.black,
                      elevation: 10.0,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          displayName,
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Image.network(
              "https://digital-display.betafore.com/$displayImage",
              fit: BoxFit.cover,
              width: double.infinity,
              height: 250,
            ),
            Container(height: 20),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {},
                  child: Text("Edit Display"),
                  style: buttonStyle1,
                ),
                ElevatedButton(
                  onPressed: () {},
                  child: Text("View Display"),
                  style: buttonStyle2,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

This is how I passed data

 Flexible(
            child: Consumer<DisplayController>(
              builder: (context, value, child) {
                //log('${value.displays[0].results?.length.toString()}');
                return GridView.count(
                  crossAxisCount: 4,
                  children: List.generate(
                      value.displays.isNotEmpty
                          ? value.displays[0].results!.length
                          : 0, (i) {
                    return DisplayCard(
                      displayName: value.displays[0].results![i].name as String,
                      displayImage: value
                          .displays[0].results![i].catalogs![0].image as String,
                      id: value.displays[0].results![i].id as int,
                    );
                  }),
                );
              },
            ),
          ),

CodePudding user response:

Your singleDisplay method is wrong. You're checking the id on the DisplayModel object's first Result object's id, instead of the _displays[0].results objects.

_displays.firstWhere((element) => element.results![0].id == id)

It should be:

Results singleDisplay(int id) {
    return _displays[0].results!.firstWhere((element) => element.id == id);
}

also, then you need to update:

Container(child: Text(display.results![0].name as String))

to:

Container(child: Text(display.name as String))
  • Related