Home > other >  how can i get the username from API using flutter?
how can i get the username from API using flutter?

Time:01-02

i want to get the username from REST API. I'm getting the ID but not username. here's my serializer.py

class OfferSeriaLizer(serializers.ModelSerializer):
    class Meta:
        model = Offer
        fields = ['id', 'offer_title', 'image', 'user', 'click', 'category']

here's my model

class Offer(models.Model):
    Offer_STATUS = (
        ("ACTIVE", "ACTIVE"),
        ("PENDING APPROVAL", "PENDING APPROVAL"),
        ("REQUIRED MODIFICATION", "REQUIRED MODIFICATION"),
        ("DENIED", "DENIED"),
        ("PAUSED", "PAUSED"),
    )

    slug = models.SlugField(unique=True, null=True)
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    offer_title = models.CharField(max_length=240)
    seo_title = models.CharField(max_length=60, null=True)
    image = models.ImageField(upload_to='images/')
    extra_images = models.ManyToManyField(ExtraImage, blank=True)
    offer_video = models.FileField(upload_to="images/", blank=True, null=True)
    document = models.FileField(upload_to="files/", null=True, blank=True)
    service = models.ForeignKey(Services, on_delete=models.CASCADE, null=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name="offers")
    sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE, null=True, blank=True)
    child_subcategory = models.ForeignKey(ChildSubcategory, on_delete=models.CASCADE, null=True, blank=True)
    packages = models.ManyToManyField(Package, through='OfferManager')
    description = models.TextField()
    # offer_rating = models.FloatField(default=0)
    is_popular = models.BooleanField(default=False, null=True)
    pop_web = models.BooleanField(default=False, null=True, blank=True)
    is_pro = models.BooleanField(default=False, null=True)
    click = models.PositiveIntegerField(null=True, blank=True, default=0)
    impressions = models.PositiveIntegerField(default=0, null=True, blank=True)
    order_count = models.PositiveIntegerField(default=0, null=True, blank=True)
    cancellation = models.PositiveIntegerField(default=0, null=True, blank=True)
    offer_status = models.CharField(max_length=200, null=True, choices=Offer_STATUS, default="PENDING APPROVAL")
    is_premium = models.BooleanField(default=False)
    is_bronze = models.BooleanField(default=False, null=True)
    bronze_created = models.DateTimeField(null=True, blank=True)
    is_silver = models.BooleanField(default=False, null=True)
    silver_created = models.DateTimeField(null=True, blank=True)
    is_gold = models.BooleanField(default=False, null=True)
    gold_created = models.DateTimeField(null=True, blank=True)
    is_pending = models.BooleanField(null=True, blank=True, default=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True)

    # From Admin Side
    has_checked = models.BooleanField(default=False)
    already_clicked = models.BooleanField(default=False)

    # Pointing Sytem DB
    points = models.PositiveIntegerField(null=True, default=0)

here's my view

class OfferApiView(APIView):
    def get(self, request):

        offers = Offer.objects.filter(offer_status="ACTIVE")

        serializer = OfferSeriaLizer(offers, many=True)


        return Response(serializer.data)

from my flutter side here's my API service code

import 'dart:convert';
import 'package:flutter/cupertino.dart';

import 'package:http/http.dart' as http;
import 'package:marketage_v2/models/offer_model.dart';

class OfferController with ChangeNotifier {
  List<OfferModel> _offers = [];

  Future<bool> getOffers() async {
    var url = Uri.parse("https://marketage.io/api/offers/");

    try {
      http.Response response = await http.get(url);
      var data = json.decode(response.body) as List;
      List<OfferModel> temp = [];
      for (var element in data) {
        OfferModel offermodel = OfferModel.fromJson(element);
        temp.add(offermodel);
      }
      _offers = temp;
      notifyListeners();
      return true;
    } catch (e) {
      return false;
    }
  }

  List<OfferModel> get offers {
    return [..._offers];
  }

  OfferModel offerDetails(id) {
    return _offers.firstWhere((element) => element.id == id);
  }
}

here's my flutter model

class OfferModel {
  late int id;
  late String offerTitle;
  late String image;
  late int category;
  late int user;
  late int click;

  OfferModel(
      {required this.id,
      required this.offerTitle,
      required this.image,
      required this.category,
      required this.user,
      required this.click});

  OfferModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    offerTitle = json['offer_title'];
    image = json['image'];
    category = json['category'];
    user = json['user'];
    click = json['click'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['offer_title'] = this.offerTitle;
    data['image'] = this.image;
    data['category'] = this.category;
    data['user'] = this.user;
    data['click'] = this.click;
    return data;
  }
}

here's my design code

// ignore: import_of_legacy_library_into_null_safe
// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace

import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';
import 'package:marketage_v2/controllers/offer_controller.dart';
import 'package:marketage_v2/screens/basic.dart';
import 'package:marketage_v2/screens/premium.dart';
import 'package:marketage_v2/screens/standard.dart';
import 'package:marketage_v2/widgets/offer_card.dart';
import 'package:provider/provider.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';

class OfferDetails extends StatelessWidget {
  static const routeName = "/offer-details";

  const OfferDetails({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final id = ModalRoute.of(context)!.settings.arguments;
    // final offer_details =
    //     Provider.of<OfferController>(context).offerDetails(id);
    final offers = Provider.of<OfferController>(context).offerDetails(id);
    final offer = Provider.of<OfferController>(context).offers;

    return Scaffold(
      backgroundColor: const Color(0xFFe6e6e6),
      body: ListView(
        children: [
          Container(
            height: 200,
            width: double.infinity,
            child: Card(
              elevation: 2,
              child: Carousel(
                dotBgColor: Colors.transparent,
                dotSize: 0.0,
                autoplay: true,
                animationDuration: const Duration(milliseconds: 2000),
                images: [
                  Image.network("https://marketage.io/${offers.image}"),
                ],
              ),
            ),
          ),
          Container(
            height: 5,
          ),
          Container(
            height: 60,
            width: double.infinity,
            child: Card(
              elevation: 2,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    children: [
                      Container(
                        child: Row(
                          children: [
                            // Container(
                            //   padding: const EdgeInsets.only(top: 5, left: 10),
                            //   child: CircleAvatar(
                            //     radius: 20,
                            //     backgroundColor: Color(0xFFe6e6e6),
                            //     backgroundImage:
                            //         Image.network("src"),
                            //   ),
                            // ),
                            Container(
                              padding: const EdgeInsets.only(left: 10, top: 5),
                              child: Text(
                                "${offers.user}",
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  Container(
                    width: 197,
                    padding: const EdgeInsets.only(right: 10),
                    // color: Colors.amber,
                    alignment: Alignment.centerRight,
                    child: const Text(
                      "Lvl 2",
                      style: TextStyle(
                        fontSize: 17,
                        fontWeight: FontWeight.w500,
                        color: Colors.black54,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Container(
            height: 5,
          ),
          Container(
            color: Colors.white,
            height: 40,
            child: const DefaultTabController(
              length: 3,
              child: TabBar(
                indicatorColor: Color(0xFF0099ff),
                labelColor: (Colors.black),
                unselectedLabelColor: Color(0xff0099ff),
                tabs: [
                  Tab(
                    child: Text(
                      'Basic',
                      style: TextStyle(
                        fontSize: 20,
                      ),
                    ),
                  ),
                  Tab(
                    child: Text(
                      'Standard',
                      style: TextStyle(
                        fontSize: 20,
                      ),
                    ),
                  ),
                  Tab(
                    child: Text(
                      'Premium',
                      style: TextStyle(
                        fontSize: 20,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          // const TabBarView(
          //   children: [
          //     Basic(),
          //     Standard(),
          //     Premium(),
          //   ],
          // ),
          Container(
            height: 5,
          ),
          Container(
            child: Card(
              elevation: 2,
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.all(7),
                    alignment: Alignment.center,
                    child: const Text(
                      "I will design and develop fully customized website",
                      style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Container(
                    height: 1,
                    color: const Color(0xFFd9d9d9),
                  ),
                  Container(
                    padding: const EdgeInsets.all(7),
                    child: const Text(
                      "I am a professional Senior Front End developer as a PSD2HTML expert with 5  years of experience In my Five years of career, I have completed more than 300 projects in different languages and frameworks. I have a strong grip as a Front End developer on HTML5, CSS3, Bootstrap4, Jquery, Javascript, SASS, React. if you want to convert your (psd to html, xd to html, sketch to html, psd to wordpress, psd to react), then you are at the right places and we can discuss the work and continue.",
                      style: TextStyle(
                        fontSize: 18,
                      ),
                    ),
                  ),
                  Container(
                    height: 15,
                  ),
                ],
              ),
            ),
          ),
          Container(
            height: 5,
          ),
          Container(
            width: double.infinity,
            child: Card(
              elevation: 3,
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.only(top: 20),
                    // alignment: Alignment.center,
                    child: const Text(
                      "About This Seller",
                      style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  Container(
                    height: 15,
                  ),
                  Container(
                    child: const CircleAvatar(
                      radius: 50,
                      backgroundColor: Color(0xFFededed),
                      backgroundImage: AssetImage("images/tsunade.png"),
                    ),
                  ),
                  Container(
                    height: 15,
                  ),
                  Container(
                    child: const Text(
                      "Sakib Ovi Chan",
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Container(
                    height: 15,
                  ),
                  Container(
                    // padding: const EdgeInsets.fromLTRB(65, 0, 0, 0),
                    child: SmoothStarRating(
                      isReadOnly: false,
                      size: 40,
                      filledIconData: Icons.star,
                      halfFilledIconData: Icons.star_half,
                      defaultIconData: Icons.star_border,
                      starCount: 5,
                      allowHalfRating: true,
                      spacing: 1,
                      color: Colors.amber,
                      borderColor: const Color(0xFFff6666),
                    ),
                  ),
                  Container(
                    height: 15,
                  ),
                  Container(
                    alignment: Alignment.center,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        minimumSize: const Size(250, 40),
                        // textStyle: const TextStyle(fontSize: 25),
                        primary: const Color(0xFF63b9eb),
                        onPrimary: const Color(0xFFffffff),
                      ),
                      child: const Text(
                        "Contact Me",
                        style: TextStyle(
                          fontSize: 22,
                          // fontWeight: FontWeight.bold,
                          color: Color(0xFFffffff),
                        ),
                      ),
                      onPressed: () {},
                    ),
                  ),
                  Container(
                    height: 20,
                  ),
                  Container(
                    padding: const EdgeInsets.only(left: 25, right: 25),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              child: const Text(
                                "From",
                                style: TextStyle(
                                  fontSize: 20,
                                  color: Colors.black54,
                                ),
                              ),
                            ),
                            Container(
                              child: const Text(
                                "Member Since",
                                style: TextStyle(
                                  fontSize: 20,
                                  color: Colors.black54,
                                ),
                              ),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              child: const Text(
                                "Bangladesh",
                                style: TextStyle(
                                  fontSize: 20,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                            Container(
                              child: const Text(
                                "Mar.07, 2021",
                                style: TextStyle(
                                  fontSize: 20,
                                  color: Colors.black,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Container(
                    height: 10,
                  ),
                ],
              ),
            ),
          ),
          Container(
            child: Card(
              elevation: 3,
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.only(top: 15),
                    alignment: Alignment.center,
                    child: const Text(
                      "My Project",
                      style: TextStyle(
                        fontSize: 23,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Container(
                    height: 15,
                  ),
                  Container(
                    alignment: Alignment.center,
                    child: Column(
                      children: [
                        Container(
                          child: const Text(
                            "gngbd.com",
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Container(
                          child: const Text(
                            "marketage.io",
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Container(
                          child: const Text(
                            "mustaqeem.com",
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Container(
                          child: const Text(
                            "urbandokan.com",
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Container(
                          child: const Text(
                            "flashoff.com",
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Container(
                          child: const Text(
                            "stackclone.com",
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Container(
                          child: const Text(
                            "bloggy.com",
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                        Container(
                          height: 10,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          // const Expanded(
          //   child: TabBarView(
          //     children: [
          //       Basic(),
          //       Standard(),
          //       Premium(),
          //     ],
          //   ),
          // ),
          // const TabBarView(
          //   children: [
          //     Basic(),
          //     Standard(),
          //     Premium(),
          //   ],
          // ),
          Container(
            height: 10,
          ),
        ],
      ),
    );
  }
}

this is where I want to show the username

Container(
                              padding: const EdgeInsets.only(left: 10, top: 5),
                              child: Text(
                                "${offers.user}",
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),

how can I get the username from this code. do I need to improve code or API ?? how can I get my username ??

CodePudding user response:

You can't access username because in your model user is assumed to be an int, while your API returns an object for user and username is inside this object. The same is true for category. For generating your dart model easiest way is to use a json to dart converter. This one supports null safety as well: https://www.jsontodart.in/

This is the model generated by this site for the json that your API returns:

class OfferModel {
OfferModel({
    required this.id,
    required this.offerTitle,
    required this.image,
    required this.user,
    required this.click,
    required this.category,
  });
  late final int id;
  late final String offerTitle;
  late final String image;
  late final User user;
  late final int click;
  late final Category category;

  OfferModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    offerTitle = json['offer_title'];
    image = json['image'];
    user = User.fromJson(json['user']);
    click = json['click'];
    category = Category.fromJson(json['category']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['offer_title'] = offerTitle;
    _data['image'] = image;
    _data['user'] = user.toJson();
    _data['click'] = click;
    _data['category'] = category.toJson();
    return _data;
  }
}

class User {
  User({
    required this.id,
    required this.password,
    required this.lastLogin,
    required this.isSuperuser,
    required this.username,
    required this.firstName,
    required this.lastName,
    required this.email,
    required this.isStaff,
    required this.isActive,
    required this.dateJoined,
    required this.groups,
    required this.userPermissions,
  });
  late final int id;
  late final String password;
  late final String lastLogin;
  late final bool isSuperuser;
  late final String username;
  late final String firstName;
  late final String lastName;
  late final String email;
  late final bool isStaff;
  late final bool isActive;
  late final String dateJoined;
  late final List<dynamic> groups;
  late final List<dynamic> userPermissions;

  User.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    password = json['password'];
    lastLogin = json['last_login'];
    isSuperuser = json['is_superuser'];
    username = json['username'];
    firstName = json['first_name'];
    lastName = json['last_name'];
    email = json['email'];
    isStaff = json['is_staff'];
    isActive = json['is_active'];
    dateJoined = json['date_joined'];
    groups = List.castFrom<dynamic, dynamic>(json['groups']);
    userPermissions = List.castFrom<dynamic, dynamic>(json['user_permissions']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['password'] = password;
    _data['last_login'] = lastLogin;
    _data['is_superuser'] = isSuperuser;
    _data['username'] = username;
    _data['first_name'] = firstName;
    _data['last_name'] = lastName;
    _data['email'] = email;
    _data['is_staff'] = isStaff;
    _data['is_active'] = isActive;
    _data['date_joined'] = dateJoined;
    _data['groups'] = groups;
    _data['user_permissions'] = userPermissions;
    return _data;
  }
}

class Category {
  Category({
    required this.id,
    required this.slug,
    required this.title,
    required this.icon,
    required this.subcategory,
  });
  late final int id;
  late final String slug;
  late final String title;
  late final String icon;
  late final List<int> subcategory;

  Category.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    slug = json['slug'];
    title = json['title'];
    icon = json['icon'];
    subcategory = List.castFrom<dynamic, int>(json['subcategory']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['slug'] = slug;
    _data['title'] = title;
    _data['icon'] = icon;
    _data['subcategory'] = subcategory;
    return _data;
  }
}

After that you can use offers.user.username to get the username.

Also I'm no backend expert, but it's probably best to omit password from user object, even though it's hashed.

  • Related