0

单击按钮后如何从 api 获取数据。基本上有两个屏幕 HomePage 和 SettingsPage,每个页面都有一个单独的 bloc 和一个存储库。主页是启动屏幕,无需单击任何按钮即可自动获取 api,在设置页面中,有两个单选按钮和一个凸起按钮。每当我选择任何单选按钮然后单击 raisebutton 它应该在 api 链接上添加该单选按钮值并在主页上获取并加载该特定数据。意味着 HomePage 已经有 HomeBloc.dart 但在设置页面中单击 raisebutton 后如何传递数据并再次加载到主页。我已经检查了 github 中的所有示例或官方页面中的文档,但不幸的是没有得到类似类型的示例。

4

1 回答 1

-1

您不会使用 flutter_bloc 发出 API 请求。你使用 http.dart。

示例(登录控制器)

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;
  }
}

然后你在你的集团内部调用它(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);
}
于 2020-01-09T23:04:43.127 回答