0

How to get the data from api after clicking on button. Basically there is two screens HomePage and SettingsPage, each page has a seperate bloc and a repository. Homepage is the launch screen which automatically fetch api without clicking any button and in settingspage where there are two radiobutton and one raisedbutton. Whenever i select any of the radiobutton and then click on raisedbutton it should add that radiobutton value on api link and fetch and load that particular data on the homepage. Means HomePage already has HomeBloc.dart but after clicking on raisedbutton in settings page how to i pass the data and once again load to homepage. I have checked all the examples in github or documentation in official page but unfortunately did not get similar type example.

SOUGAT RIYADH
  • 562
  • 2
  • 10
  • 26

1 Answers1

-1

You don't make API requests using flutter_bloc. You use http.dart.

Example (LoginController)

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:pmd_mobile/model/api_route.dart';

class LoginController {
  static Future<http.Response> login(
      {@required String email, @required String password}) async {
    var params = {
      'email': email,
      'password': password,
    };

    var response = await http.post(ApiRoute.LOGIN,
        body: json.encode(params));
    return response;
  }
}

Then you call it inside your bloc (LoginBloc)

class LoginBloc extends Bloc<LoginEvent, LoginState> {
  final BuildContext context;
  final UserRepository userRepository;
  final AuthBloc authBloc;

  LoginBloc(
      {@required this.context,
      @required this.userRepository,
      @required this.authBloc})
      : assert(userRepository != null),
        assert(authBloc != null);

  LoginState get initialState => LoginInitial();

  @override
  Stream<LoginState> mapEventToState(LoginEvent event) async* {
    if (event is LoginButtonPressed) {
      yield LoginProcessing();

      await Future.delayed(const Duration(milliseconds: 250));

      try {
        var loginResponse =
            await _attemptLogin(userRepository, event.email, event.password);

        if (loginResponse['data']) {
          yield LoginInitial();
        } else {
          yield LoginFailure(message: 'Login failed.');
        }
      } catch (error, stackTrace) {
        print(error);
        print(stackTrace);

        await Future.delayed(const Duration(seconds: 1));
        yield LoginFailure(
            message: 'Login failed. Please check your internet connection.');
      }
    }
  }
}

_attemptLogin(
    UserRepository userRepository, String email, String password) async {
  final response = await userRepository.authenticate(
    email: email,
    password: password,
  );

  return json.decode(response.body);
}
Rick
  • 2,003
  • 4
  • 16
  • 28