flutter bloc list

flutter bloc list :

Screenshot 1 :

flutter bloc list

Screenshot 2 :

flutter bloc list

Screenshot 3 :

flutter bloc list

models package

– item.dart
– models.dart

item.dart

import 'package:meta/meta.dart';
import 'package:equatable/equatable.dart';

class Item extends Equatable {
  final String id;
  final String value;
  final bool isDeleting;

  const Item({
    @required this.id,
    @required this.value,
    this.isDeleting = false,
  });

  Item copyWith({
    String id,
    String value,
    bool isDeleting,
  }) {
    return Item(
      id: id ?? this.id,
      value: value ?? this.value,
      isDeleting: isDeleting ?? this.isDeleting,
    );
  }

  @override
  List<Object> get props => [id, value, isDeleting];

  @override
  String toString() =>
      'Item { id: $id, value: $value, isDeleting: $isDeleting }';
}

models.dart

export 'item.dart';

bloc package

– bloc.dart
– list_bloc.dart
– list_event.dart
– list_state.dart
– simple_bloc_delegate.dart

bloc.dart

export 'list_bloc.dart';
export 'list_event.dart';
export 'list_state.dart';
export 'simple_bloc_delegate.dart';

list_bloc.dart

import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:flutter_complex_list/repository.dart';
import 'package:flutter_complex_list/models/models.dart';
import 'package:flutter_complex_list/bloc/bloc.dart';

class ListBloc extends Bloc<ListEvent, ListState> {
  final Repository repository;

  ListBloc({@required this.repository});

  @override
  ListState get initialState => Loading();

  @override
  Stream<ListState> mapEventToState(
    ListEvent event,
  ) async* {
    if (event is Fetch) {
      try {
        final items = await repository.fetchItems();
        yield Loaded(items: items);
      } catch (_) {
        yield Failure();
      }
    }
    if (event is Delete) {
      final listState = state;
      if (listState is Loaded) {
        final List<Item> updatedItems =
            List<Item>.from(listState.items).map((Item item) {
          return item.id == event.id ? item.copyWith(isDeleting: true) : item;
        }).toList();
        yield Loaded(items: updatedItems);
        repository.deleteItem(event.id).listen((id) {
          add(Deleted(id: id));
        });
      }
    }
    if (event is Deleted) {
      final listState = state;
      if (listState is Loaded) {
        final List<Item> updatedItems = List<Item>.from(listState.items)
          ..removeWhere((item) => item.id == event.id);
        yield Loaded(items: updatedItems);
      }
    }
  }
}

list_event.dart

import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

abstract class ListEvent extends Equatable {
  const ListEvent();

  @override
  List<Object> get props => [];
}

class Fetch extends ListEvent {}

class Delete extends ListEvent {
  final String id;

  const Delete({@required this.id});

  @override
  List<Object> get props => [id];

  @override
  String toString() => 'Delete { id: $id }';
}

class Deleted extends ListEvent {
  final String id;

  const Deleted({@required this.id});

  @override
  List<Object> get props => [id];

  @override
  String toString() => 'Deleted { id: $id }';
}

list_state.dart

import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

import 'package:flutter_complex_list/models/models.dart';

abstract class ListState extends Equatable {
  const ListState();

  @override
  List<Object> get props => [];
}

class Loading extends ListState {}

class Loaded extends ListState {
  final List<Item> items;

  const Loaded({@required this.items});

  @override
  List<Object> get props => [items];

  @override
  String toString() => 'Loaded { items: ${items.length} }';
}

class Failure extends ListState {}

simple_bloc_delegate.dart

import 'package:bloc/bloc.dart';

class SimpleBlocDelegate extends BlocDelegate {
  @override
  void onEvent(Bloc bloc, Object event) {
    super.onEvent(bloc, event);
    print(event);
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {
    super.onError(bloc, error, stacktrace);
    print(error);
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print(transition);
  }
}

repository.dart

import 'dart:async';
import 'dart:math';
import 'package:flutter_complex_list/models/models.dart';

class Repository {
  final _random = Random();

  int _next(int min, int max) => min + _random.nextInt(max - min);

  Future<List<Item>> fetchItems() async {
    await Future.delayed(Duration(seconds: _next(1, 5)));
    return List.of(_generateItemsList());
  }

  List<Item> _generateItemsList() {
    final List<Item> items = [];

    items.add(Item(id: '1', value: 'C'));
    items.add(Item(id: '2', value: 'C++'));
    items.add(Item(id: '3', value: 'DATA STRUCTURE'));
    items.add(Item(id: '4', value: 'PHP'));
    items.add(Item(id: '5', value: 'ANDROID'));

    return items;
  }

  Stream<String> deleteItem(String id) async* {
    await Future.delayed(Duration(seconds: _next(1, 5)));
    yield id;
  }
}

pubspec.yaml

name: flutter_complex_list
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_bloc:
  equatable: ^0.6.0

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

main.dart

import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'package:flutter_complex_list/bloc/bloc.dart';
import 'package:flutter_complex_list/models/models.dart';
import 'package:flutter_complex_list/repository.dart';

void main() {
  BlocSupervisor.delegate = SimpleBlocDelegate();
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Complex List',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Complex List'),
        ),
        body: BlocProvider(
          builder: (context) =>
              ListBloc(repository: Repository())..add(Fetch()),
          child: HomePage(),
        ),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ListBloc, ListState>(
      builder: (context, state) {
        if (state is Failure) {
          return Center(
            child: Text('Oops something went wrong!'),
          );
        }
        if (state is Loaded) {
          if (state.items.isEmpty) {
            return Center(
              child: Text('no content'),
            );
          }
          return ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return ItemTile(
                item: state.items[index],
                onDeletePressed: (id) {
                  BlocProvider.of<ListBloc>(context).add(Delete(id: id));
                },
              );
            },
            itemCount: state.items.length,
          );
        }
        return Center(
          child: CircularProgressIndicator(),
        );
      },
    );
  }
}

class ItemTile extends StatelessWidget {
  final Item item;
  final Function(String) onDeletePressed;

  const ItemTile({
    Key key,
    @required this.item,
    @required this.onDeletePressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Text('${item.id}'),
      title: Text(item.value),
      trailing: item.isDeleting
          ? CircularProgressIndicator()
          : IconButton(
              icon: Icon(Icons.delete, color: Colors.red),
              onPressed: () => onDeletePressed(item.id),
            ),
    );
  }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in