flutter中使用redux之多界面互动

上一篇文章,我们介绍了如何在flutter中使用redux。在上一篇文章的例子中,我们使用了单界面集成redux,但是在实际项目中,我们通常涉及多个模块,每个模块涉及多个界面,那么如何使用redux整合模块,并实现模块和界面间的消息传递呢?

例子:登录

接着上篇文章,这次的例子稍微复杂一点:

目标:

  • 实现登录界面,实现基本登录逻辑
  • 成功之后将结果通知到其他界面

clipboard.png

先将AppState等状态有关的移动到reducers.dart,创建LoginPage.dart

LoginPage.dart代码如下:

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter_use_redux/reducers.dart';
import 'package:redux/redux.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';


typedef Future CallLogin(String account,String pwd);

class LoginPageState extends State<LoginPage>{

  String _account;
  String _pwd;



  bool isLogin;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("登录"),
      ),
      body: new Form(
          onChanged: (){
            print("changed");
          },
          onWillPop: () async{
            return true;
          },
          child: new Padding(padding: new EdgeInsets.all(10.0),child: new Column(

            children: <Widget>[
              new TextFormField( decoration:new InputDecoration(labelText: "请输入账号") ,
                onSaved: (String value){
                 _account = value;
                },  ///保持一下输入的账号
                validator: (String value)=> value.isEmpty ? "请输入账号" : null, ),
              new TextFormField(decoration:new InputDecoration(labelText: "请输入密码"),
                  onSaved: (String value)=>_pwd = value, ///保持一下输入的密码
                  validator: (String value)=> value.isEmpty ? "请输入密码" : null),
              new FormField(builder: (FormFieldState s){
                return new Center(
                  child: new RaisedButton(onPressed: () async{

                  FormState state = Form.of(s.context);
                  if(state.validate()){
                    //如果验证成功,那么执行登录逻辑
                    state.save();
                    print("Login success $_account" );
                    //这里交给设置好的逻辑去执行操作
                    try{
                      await widget.callLogin(_account,_pwd);
                      showDialog(context: context,builder: (c){

                        return new CupertinoAlertDialog(
                          title: new Text("登录成功"),
                          actions: <Widget>[
                            new Center(
                              child: new RaisedButton(
                                onPressed:(){
                                  Navigator.of(context).pop();
                                  Navigator.of(context).pop();
                                },
                                child: new Text("ok"),
                              )
                            )
                          ],
                        );

                      });
                    //  Navigator.of(context).pop();
                    }catch(e){
                      showDialog(context: context,builder: (c){

                        return new CupertinoAlertDialog(
                          title: new Text("登录失败$e"),
                          actions: <Widget>[
                            new Center(
                                child: new RaisedButton(
                                  onPressed:(){
                                    Navigator.of(context).pop();
                                  },
                                  child: new Text("ok"),
                                )
                            )
                          ],
                        );

                      });
                      ///登录失败,提示一下用户
                      print("登录失败! $e");
                    }

                  }

                },child: new Text("提交"),)
                );
              })
            ],

          ),)),
    );
  }

}

class LoginPage extends StatefulWidget{

  CallLogin callLogin;


  LoginPage({this.callLogin});

  @override
  State<StatefulWidget> createState() {
    return new LoginPageState();
  }

}
注意:这个组件其实并没有使用redux,登录逻辑使用外部传递过来的函数来处理:
 CallLogin callLogin;
  LoginPage({this.callLogin});

 ...
//执行登录逻辑
     await widget.callLogin(_account,_pwd);
 ...                 
为什么要这么做呢?好处有哪些?
  • 减少组件之间的依赖关系
  • 减少本类的职责,将本类的职责变成只展示ui
  • 本类可单独单元测试,单独工作,只要传进来一个模拟的逻辑函数
那么在哪里将登录逻辑传递进来呢?

···
routes: {

    "login":(BuildContext context)=>new StoreConnector(builder: ( BuildContext context,Store<AppState> store ){

      return new LoginPage(callLogin: (String account,String pwd) async{
        print("正在登录,账号$account,密码:$pwd");
        // 为了模拟实际登录,这里等待一秒
        await new Async.Future.delayed(new Duration(milliseconds: 1000));
        if(pwd != "123456"){
          throw ("登录失败,密码必须是123456");
        }
        print("登录成功!");
        store.dispatch(new LoginSuccessAction(account: account));

      },);
    }, converter: (Store<AppState> store){
      return store;
    }),

···

在导入这个登录组件到应用程序路由上面的时候,这个时候将逻辑和Store进行对接,这样做,就将逻辑和ui彻底的分开了。

这里涉及到异步操作,那么就会遇到所谓“副作用”问题。
随着项目的增大,reducer也会越来越大,那么有什么办法可以管理呢?
这些问题我们改天再分享。

附件:

老规矩,代码在这里:
https://github.com/jzoom/flut...

如有疑问,请加qq群854192563讨论


flutter探索之路
本专栏分享、收集flutter优秀中文资料,欢迎一起探索flutter。

A simple way to solving problems is using tools like docker/Spring boot/React Native/React/Vue… T...

1.2k 声望
335 粉丝
0 条评论
推荐阅读
CSplitterWnd动态分割
静态分割不提了,网上一大堆。关键是动态分割要怎么办?1、从未切分到切分2、从切分到未切分3、从切分状态m到切分状态n的转变比如这里要实现一个通达信的看盘窗口,分成主窗口和指标窗口。指标窗口可随时关闭,也...

jzoom阅读 1.1k

手把手教你写一份优质的前端技术简历
不知不觉一年一度的秋招又来了,你收获了哪些大厂的面试邀约,又拿了多少offer呢?你身边是不是有挺多人技术比你差,但是却拿到了很多大厂的offer呢?其实,要想面试拿offer,首先要过得了简历那一关。如果一份简...

tonychen152阅读 17.7k评论 5

封面图
正则表达式实例
收集在业务中经常使用的正则表达式实例,方便以后进行查找,减少工作量。常用正则表达式实例1. 校验基本日期格式 {代码...} {代码...} 2. 校验密码强度密码的强度必须是包含大小写字母和数字的组合,不能使用特殊...

寒青56阅读 8.4k评论 11

JavaScript有用的代码片段和trick
平时工作过程中可以用到的实用代码集棉。判断对象否为空 {代码...} 浮点数取整 {代码...} 注意:前三种方法只适用于32个位整数,对于负数的处理上和Math.floor是不同的。 {代码...} 生成6位数字验证码 {代码...} ...

jenemy48阅读 6.9k评论 12

从零搭建 Node.js 企业级 Web 服务器(十五):总结与展望
总结截止到本章 “从零搭建 Node.js 企业级 Web 服务器” 主题共计 16 章内容就更新完毕了,回顾第零章曾写道:搭建一个 Node.js 企业级 Web 服务器并非难事,只是必须做好几个关键事项这几件必须做好的关键事项就...

乌柏木75阅读 7k评论 16

再也不学AJAX了!(二)使用AJAX ① XMLHttpRequest
「再也不学 AJAX 了」是一个以 AJAX 为主题的系列文章,希望读者通过阅读本系列文章,能够对 AJAX 技术有更加深入的认识和理解,从此能够再也不用专门学习 AJAX。本篇文章为该系列的第二篇,最近更新于 2023 年 1...

libinfs42阅读 6.8k评论 12

封面图
从零搭建 Node.js 企业级 Web 服务器(一):接口与分层
分层规范从本章起,正式进入企业级 Web 服务器核心内容。通常,一块完整的业务逻辑是由视图层、控制层、服务层、模型层共同定义与实现的,如下图:从上至下,抽象层次逐渐加深。从下至上,业务细节逐渐清晰。视图...

乌柏木45阅读 8.5k评论 6

A simple way to solving problems is using tools like docker/Spring boot/React Native/React/Vue… T...

1.2k 声望
335 粉丝
宣传栏