我如何从不同页面获取数据并使用flutter中的共享首选项将数据呈现到另一个页面中

时间:2019-09-18 05:17:21

标签: flutter sharedpreferences flutter-layout flutter-dependencies flutter-test

当我填写了第一页的所有详细信息时,这里就有一个注册流程,当我按下一步时,它将存储到共享的首选项中,并转到下一页。填满所有页面并结束页面的末尾后,我想在扑朔迷离中使用共享首选项打印所有数据。

这里是项目的完整源代码,您可以在其中获取所有带有代码的页面, https://github.com/rutvikgumasana/signup

3 个答案:

答案 0 :(得分:1)

只需将导航中的数据从一个类传递到另一类,只需看看下面的代码我做了一些更改

注册模型课程

  import 'dart:convert';

  SignUpModel signUpModelFromJson(String str) => SignUpModel.fromJson(json.decode(str));

  String signUpModelToJson(SignUpModel data) => json.encode(data.toJson());

  class SignUpModel {
 String businessLegalName;
 int businessPhoneNo;
 int businessYear;

 SignUpModel({
   this.businessLegalName,
   this.businessPhoneNo,
   this.businessYear,
 });

 factory SignUpModel.fromJson(Map<String, dynamic> json) => SignUpModel(
      businessLegalName: json["business_legal_name"] == null ? null :    json["business_legal_name"],
      businessPhoneNo: json["business_phone_no"] == null ? null : json["business_phone_no"],
      businessYear: json["business_year"] == null ? null : json["business_year"],
    );

 Map<String, dynamic> toJson() => {
   "business_legal_name": businessLegalName == null ? null : businessLegalName,
   "business_phone_no": businessPhoneNo == null ? null : businessPhoneNo,
   "business_year": businessYear == null ? null : businessYear,
 };
  }

BspSignupPage类的更改

SignUpModel model = SignUpModel();
                  model.businessLegalName = clrbusinessname.text;
                  model.businessPhoneNo = clrphone.text as int;
                  model.businessYear = clrestablishedyear.text as int;
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => BspUnlicensedSignupPage(
                        signUpModel: model,
                      ),
                    ),
                  );

BspUnlicensedSignupPage中的更改

class BspUnlicensedSignupPage extends StatefulWidget {
  static const String routeName = "/bspUnlicensedSignup";
  final SignUpModel signUpModel;

  BspUnlicensedSignupPage({
    Key key,
    @required this.signUpModel,
  }) : super(key: key);

  @override
  _BspUnlicensedSignupPageState createState() =>
      _BspUnlicensedSignupPageState();
}

以及处于初始化状态的方法

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    debugPrint('Page1 Data: ${widget.signUpModel.businessLegalName}');
  }    

答案 1 :(得分:0)

我建议您应仅使用一页,并为此目的使用PageViewIndexedStack。 使用IndexedStack,一次只能显示一个子窗口小部件,并在单击按钮时切换当前索引。但是在这种情况下,您必须自己创建动画,因为IndexedStack不提供默认动画。

如果使用PageView,则具有默认动画,也可以在单击按钮时将其切换。 它还为您提供了滑动手势,可以使用

禁用该手势
  

PageView(physics:new NeverScrollableScrollPhysics())

答案 2 :(得分:0)

尝试一下, 每当用户单击下一步/提交按钮时,创建一个对象类(POJO类)并将数据存储在共享首选项中。然后,进入最终屏幕后,从首选项中获取数据并显示。