簡體   English   中英

flutter - bloc - 如何在我的 Ui 中使用 FutureBuilder 來正確實現 Bloc 架構

[英]flutter - bloc - how can I use FutureBuilder in my Ui to properly implement Bloc Architecture

我是 flutter 和 Bloc 架構的新手,我正在嘗試將 Bloc 用於我的登錄功能。 我正在嘗試調用我的 Bloc 文件中的函數,但我不知道該怎么做。 如果您能幫我看看我在使用 Bloc 時是否還有其他問題,我也會很高興。 這是我的 Ui 的代碼:

MaterialButton(
                      color: Colors.deepPurple,
                      minWidth: screenAwareSize(500, context),
                      onPressed: () {
                        _submitForm(authBloc, user, pass);
                      },
 void _submitForm(AuthBloc authBloc, String user, String pass) async {
    formKey.currentState.save();
    if (formKey.currentState.validate()) {
      var response = await authBloc.login(user, pass);
//when I print(response) it shows null


    }
  }

這是我的集團班級:

class AuthBloc extends MainBloc {
  final Repo _repo = Repo();
  PublishSubject<Future<UserModel>> _authController = new PublishSubject<Future<UserModel>>();
  Observable<Future<UserModel>> get auth => _authController.stream;
  login(String user, String pass) async {

    Future<UserModel> item = await _repo.login(user, pass);
    _authController.sink.add(item);
  }

  dispose() {
    _authController.close();
  }
}

AuthBloc authBloc = new AuthBloc();

這是我的 API 類:

class API{
 Future<UserModel> login(String user, String pass) async {
    var response =
        await client.get(base_url + "login.php?user=${user}&pass=${pass}");
    return UserModel.fromJSON(json.decode(response.body));
  }}

這是我的回購類:

 class Repo {
    final API api = new API();
  login(String user, String pass) async => await api.login(user, pass);}

我將首先嘗試解釋 BLOC 組件應該做什么,盡可能短(並且盡可能瑣碎)。

  • UI 屏幕 - 明顯地向用戶顯示數據
  • BLOC(或 ViewModel) - 決定如何向用戶顯示數據,是否將文本加粗,是否顯示錯誤,是否進入下一個屏幕。
  • Repo - 決定向用戶顯示什么數據(我們是否顯示來自數據庫的內容,我們是否從 API 獲取它,我們是否顯示紅色的產品?)

根據您的應用程序的功能,您也可以擁有其他組件,例如:

  • 網絡 - 執行 API 請求並將響應轉換為模型,這應該只能從 repos 訪問,並且該組件唯一應該做的就是從 repo(headers、body、url)接收數據並將數據以以下形式返回到 repo一個模型(您可以查看下面的代碼)。
  • 數據庫 - 對數據庫執行 CRUD 操作,同樣只能從 repo 訪問。
  • 傳感器 - 從本機傳感器讀取數據,同樣只能從 repo 訪問。

現在,我建議也將 BLOC 模式與依賴注入一起使用,否則它是無用的。 使用 DI,您可以模擬所有組件直到 UI,並且可以很容易地對所有代碼進行單元測試。

另外,我認為將 RxDart(庫)與 Streams/Future(dart 等效於 RxDart 庫)混合使用是沒有意義的。 首先,我建議只使用其中一個,並且根據您的代碼片段,我建議更好地了解如何使用 Rx。

所以,下面你有一個關於我將如何使用塊模式進行登錄的小代碼片段(檢查代碼注釋也很好:))。

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class TheUIScreen extends StatefulWidget {
  @override
  _TheUIScreenState createState() => _TheUIScreenState();
}

class _TheUIScreenState extends State<TheUIScreen> {
  //TODO: for repo, block, networking, we used dependecy injection, here we have to create and init all the dependecies;

  TheAuthBlock _block;

  @override
  void initState() {
    super.initState();
    TheAuthAPI api = TheAuthAPI();
    TheAuthRepo repo =
        TheAuthRepo(theAuthAPI: api); // we could also do repo = TheAuthRepo();
    _block =
        TheAuthBlock(repo: repo); // we could also do _block = TheAuthBlock();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: RaisedButton(onPressed: () {
        _block.loginUser("test", "test").then((actualUser) {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return TestRoute(); // or do whatever action you need, the user is logged in
          }));
        }).catchError((error) {
          //show error, something went wrong at login;
        });
      }),
    );
  }
}

class TheAuthBlock {
  final TheAuthRepo repo;

  TheAuthBlock({this.repo = const TheAuthRepo()});

  Future<UserModel> loginUser(String email, String password) {
    return repo.login(email, password).then((userModel) {
      //TODO: here we decide HOW to display the user, you might want to transfor the UserModel into a model that's used only for UI.
      //In any way, here you should do all the processing, the UI only should only display the data, not manipulate it.
    });
  }
}

class TheAuthRepo {
  final TheAuthAPI theAuthAPI;

  const TheAuthRepo(
      {this.theAuthAPI =
          const TheAuthAPI()}); // THIS would be the default constructor but it will alow us to test it using unit tests.

  Future<UserModel> login(String email, String password) {
    //TODO: here you could also check if the user is already logged in and send the current user as a response
    if (email.isNotEmpty && password.isNotEmpty) {
      return theAuthAPI.login(email, password).then((userModel) {
        //TODO: you can do extra processing here before returning the data to the block;
      });
    } else {
      return Future.error(
          "Well you can't login with empty ddata"); // TODO: you can return differetn errors for email or pwd;
    }
  }
}

class TheAuthAPI {
  final String url;

  const TheAuthAPI({this.url = "https://my.cool.api/login"});

  Future<UserModel> login(String email, String pwd) {
    // TODO: note you return a future from this method since the login will return only once (like almost all http calls)
    Map<String, String> headers = Map(); // TODO: set any headers you need here
    Map<String, String> body = {
      "email": email,
      "pwd": pwd
    }; // TODO: change the body acordingly
    return http.post("THE URL", headers: headers, body: body).then((response) {
      //TODO: parse response here and return it
      return UserModel("test",
          "test"); // this should be generated from the response not like this
    });
  }
}

class UserModel {
  final String email;

  UserModel(this.email, this.pass);

  final String pass;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM