📒
Mobile Development Reference-TCE-C01
  • Welcome
  • Introduction
    • Project Description
  • First Steps
    • Creating Project
    • Setting up Workspace
      • Project structure
      • Setting up the app
  • Routing
    • Setting up auto route
    • Creating the first screen
    • Setting up router
    • Adding router to Material App
  • Products Feature
    • Creating models
      • Introduction to freezed
      • Introduction to JSON annotations
      • Creating products model
    • Creating products cubit
      • Creating Products States
      • Creating Products Cubit
      • Implementing Get Products Functionality
    • Creating products repository
      • Setting up Dio
      • Making your first http request with DIO
    • Implementing Products Screen UI
      • Adding Products Grid
      • Adding Products Tile
      • Add Products Error Widget
    • Consuming the products cubit
      • Setting up Dependency injection
      • Creating Bloc Provider for ProductsCubit
      • Mapping Products Cubit states to UI
  • Testing
    • Widget Testing
    • Unit Testing
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Products Feature
  2. Creating products cubit

Implementing Get Products Functionality

Get Products

Import

import 'package:dio/dio.dart';
import 'package:techamp_flutter_shopping_app/app.dart';

Create an abstract class of ProductRepository

abstract class ProductRepository {
  Future<List<Product>> getAll();
}

Implement the abstract class

class ProductRepositoryImpl implements ProductRepository {
  final Dio _dio;

  const ProductRepositoryImpl(this._dio) : assert(_dio != null);

  @override
  Future<List<Product>> getAll() async {
    try {
      final response = await _dio.get('products');
      final List productsJson = response.data;
      return productsJson.map((json) => Product.fromJson(json)).toList();
    } on DioError catch (_) {
      throw const AppError('Network error');
    } on dynamic catch (_) {
      throw const AppError('Something went wrong.');
    }
  }
}

PreviousCreating Products CubitNextCreating products repository

Last updated 4 years ago

Was this helpful?