单击按钮后如何从api获取数据。基本上有两个屏幕,即HomePage和SettingsPage,每个页面都有一个单独的块和一个存储库。主页是启动屏幕,无需单击任何按钮即可自动获取api,在设置页面中有两个单选按钮和一个凸起按钮。每当我选择任何一个单选按钮然后单击凸起按钮时,都应在api链接上添加该单选按钮值,并在主页上获取并加载该特定数据。 意味着Homepage已经具有HomeBloc.dart,但是在设置页面中单击凸起按钮后,如何传递数据并再次加载到主页。我已经检查了github上的所有示例或官方页面上的文档,但是不幸的是没有得到类似的类型示例。
答案 0 :(得分:0)
您不使用flutter_bloc发出API请求。您使用http.dart。
示例(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;
}
}
然后您在自己的集团(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);
}