flutter - 如何将数据从表单传递到下一个屏幕?

标签 flutter dart

我正在构建一个应用程序,该应用程序的格式很长,包含许多文本字段,因此我将文本字段分为多个屏幕。它具有三个屏幕,第一个屏幕具有一些常用的文本字段,例如电话,网站,电子邮件等。第二个屏幕具有更多的文本字段,并且与第三个屏幕相同。我试图在不同的屏幕上最后显示三种形式的所有详细信息。

First screen

enter image description here

enter image description here

我想在其他页面上单击“完成”按钮时最后显示所有详细信息。

这是具有第一种形式的第一个屏幕的代码:-

import 'package:flutter/material.dart';
import 'package:instaskool/model.dart';
import 'package:validators/validators.dart' as validator;
import 'package:instaskool/home_screens/homescreen_student.dart';
import 'package:instaskool/home_screens/homescreen_school.dart';
import 'package:instaskool/screens/school_signup_two.dart';



class SchoolReg extends StatefulWidget {
  @override
  _SchoolRegState createState() => _SchoolRegState();
}
class _SchoolRegState extends State<SchoolReg> {
  final _formKey = GlobalKey<FormState>();
  School school = School();
@override
  Widget build(BuildContext context) {
return Scaffold(


  body: SingleChildScrollView(
      child: new Form(

          key: _formKey,

          child: Column(

            children: <Widget>[

              Container(

                margin: EdgeInsets.only(top: 130),
                alignment: Alignment.topCenter,


    child:  MyTextFormField(

                        hintText: 'School name',

                        validator: (String value) {

                          if (value.isEmpty) {

                            return 'Enter your school name';

                          }

                          return null;

                        },

                        onSaved: (String value) {

                          school.schoolName = value;

                        },

                      ),


              ),


                  MyTextFormField(

                        hintText: 'Phone',

                        validator: (String value) {

                          if (value.isEmpty) {

                            return 'Enter the phone number';

                          }

                          return null;

                        },

                        onSaved: (String value) {

                          school.schoolPhone = value;

                        },
                  ),


                   MyTextFormField(

                        hintText: 'Email',

                        validator: (String value) {

                          if (value.isEmpty) {

                            return 'Enter the email address';

                          }

                          return null;

                        },

                        onSaved: (String value) {

                          school.schoolEmail = value;

                        },

                      ),


            MyTextFormField(
                hintText: 'School Website',

                isEmail: true,

                validator: (String value) {

                  if (value.isEmpty) {

                    return "Enter the school's website";

                  }

                  return null;

                },

                onSaved: (String value) {

                  school.schoolWebsite = value;

                },

              ),



              RaisedButton(

                color: Colors.blueAccent,



                onPressed: () {

                  if (_formKey.currentState.validate()) {

                    _formKey.currentState.save();

    Navigator.push(

                        context,

                        MaterialPageRoute(

                            builder: (context) => SchoolRegTwo()));

                  }

                },

                child: Text(

                  'Next',

                  style: TextStyle(

                    color: Colors.white,

                  ),

                ),

              )

            ],

          ),

        ),
  ),
);
  }
}
class MyTextFormField extends StatelessWidget {
  final String hintText;
  final Function validator;
  final Function onSaved;
  final bool isPassword;
  final bool isEmail;
MyTextFormField({
    this.hintText,
    this.validator,
    this.onSaved,
    this.isPassword = false,
    this.isEmail = false,
  });
@override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: TextFormField(
        decoration: InputDecoration(
          hintText: hintText,
          contentPadding: EdgeInsets.all(15.0),
          border: InputBorder.none,
          filled: true,
          fillColor: Colors.grey[200],
        ),
        obscureText: isPassword ? true : false,
        validator: validator,
        onSaved: onSaved,
        keyboardType: isEmail ? TextInputType.emailAddress : TextInputType.text,
      ),
    );
  }
}

这是第二种形式的代码:-
import 'package:flutter/material.dart';
import 'package:instaskool/model.dart';
import 'package:validators/validators.dart' as validator;
import 'package:instaskool/home_screens/homescreen_student.dart';
import 'package:instaskool/home_screens/homescreen_school.dart';
import 'package:instaskool/screens/school_signup_three.dart';


class SchoolRegTwo extends StatefulWidget {



  @override
  _SchoolRegTwoState createState() => _SchoolRegTwoState();
}
class _SchoolRegTwoState extends State<SchoolRegTwo> {
  final _formKey = GlobalKey<FormState>();
  SchoolDet schooldet = SchoolDet();
@override
  Widget build(BuildContext context) {
return Scaffold(


  body: SingleChildScrollView(
      child: new Form(

          key: _formKey,

          child: Column(

            children: <Widget>[

              Container(

                margin: EdgeInsets.only(top: 130),
                alignment: Alignment.topCenter,


    child:  MyTextFormField(

                        hintText: 'School address 1',

                        validator: (String value) {

                          if (value.isEmpty) {

                            return "Enter your school's address";

                          }

                          return null;

                        },

                        onSaved: (String value) {

                          schooldet.addressOne = value;

                        },

                      ),


              ),


                  MyTextFormField(

                        hintText: 'School address 2',

                        validator: (String value) {

                          if (value.isEmpty) {

                            return "Enter the school's address";

                          }

                          return null;

                        },

                        onSaved: (String value) {

                          schooldet.addressTwo = value;

                        },
                  ),


                   MyTextFormField(

                        hintText: 'City',

                        validator: (String value) {

                          if (value.isEmpty) {

                            return 'Enter the city';

                          }

                          return null;

                        },

                        onSaved: (String value) {

                          schooldet.city = value;

                        },

                      ),


            MyTextFormField(
                hintText: 'Pincode',

                isEmail: true,

                validator: (String value) {

                  if (value.isEmpty) {

                    return "Enter the pincode";

                  }

                  return null;

                },

                onSaved: (String value) {

                  schooldet.pincode = value;

                },

              ),




            MyTextFormField(
                hintText: 'State',

                isEmail: true,

                validator: (String value) {

                  if (value.isEmpty) {

                    return "Enter the state";

                  }

                  return null;

                },

                onSaved: (String value) {

                  schooldet.state = value;

                },

              ),


              RaisedButton(

                color: Colors.blueAccent,

                onPressed: () {

                  if (_formKey.currentState.validate()) {

                    _formKey.currentState.save();

    Navigator.push(

                        context,

                        MaterialPageRoute(

                            builder: (context) => SchoolRegThree(schooldet: this.schooldet)));

                  }

                },

                child: Text(

                  'Next',

                  style: TextStyle(

                    color: Colors.white,

                  ),

                ),

              )

            ],

          ),

        ),
  ),
);
  }
}
class MyTextFormField extends StatelessWidget {
  final String hintText;
  final Function validator;
  final Function onSaved;
  final bool isPassword;
  final bool isEmail;
MyTextFormField({
    this.hintText,
    this.validator,
    this.onSaved,
    this.isPassword = false,
    this.isEmail = false,
  });
@override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: TextFormField(
        decoration: InputDecoration(
          hintText: hintText,
          contentPadding: EdgeInsets.all(15.0),
          border: InputBorder.none,
          filled: true,
          fillColor: Colors.grey[200],
        ),
        obscureText: isPassword ? true : false,
        validator: validator,
        onSaved: onSaved,
        keyboardType: isEmail ? TextInputType.emailAddress : TextInputType.text,
      ),
    );
  }
}

这是第三种形式的代码:-
import 'package:flutter/material.dart';
import 'package:instaskool/model.dart';
import 'package:validators/validators.dart' as validator;
import 'package:instaskool/home_screens/homescreen_student.dart';
import 'package:instaskool/home_screens/homescreen_school.dart';
import 'package:instaskool/screens/school_signup_three.dart';
import 'package:instaskool/screens/school_code.dart';


class SchoolRegThree extends StatefulWidget {

   School school;
   SchoolRegThree({this.school, SchoolDet schooldet});

  @override
  _SchoolRegThreeState createState() => _SchoolRegThreeState();
}
class _SchoolRegThreeState extends State<SchoolRegThree> {
  final _formKey = GlobalKey<FormState>();
  SchoolUser schooluser = SchoolUser();
@override
  Widget build(BuildContext context) {
return Scaffold(


  body: SingleChildScrollView(
      child: new Form(

          key: _formKey,

          child: Column(

            children: <Widget>[

              Container(
                margin: EdgeInsets.only(top: 100),
                  child: MyTextFormField(


                  hintText: 'Username',

                  isPassword: true,

                  validator: (String value) {

                    if (value.length < 5) {

                      return 'Username should be at least 5 characters long';

                    }

    _formKey.currentState.save();

    return null;

                  },

                  onSaved: (String value) {

                    schooluser.username = value;

                  },

                ),
              ),

              MyTextFormField(

                hintText: 'New Password',

                isPassword: true,

                validator: (String value) {

                  if (value.length < 7) {

                    return 'Password should be at least 7 characters long';

                  } else if (schooluser.password != null) {

                    print(value);

                    print(schooluser.password);


                  }

    return null;

                },

                onSaved: (String value) {

                  schooluser.password = value;

                },

              ),

              RaisedButton(

                color: Colors.blueAccent,

                onPressed: () {

                  if (_formKey.currentState.validate()) {

                    _formKey.currentState.save();

    Navigator.push(

                        context,

                        MaterialPageRoute(

                            builder: (context) => ResultSchool(schooluser: this.schooluser)));

                  }

                },

                child: Text(

                  'Done',

                  style: TextStyle(

                    color: Colors.white,

                  ),

                ),

              )

            ],

          ),

        ),
  ),
);
  }
}
class MyTextFormField extends StatelessWidget {
  final String hintText;
  final Function validator;
  final Function onSaved;
  final bool isPassword;
  final bool isEmail;
MyTextFormField({
    this.hintText,
    this.validator,
    this.onSaved,
    this.isPassword = false,
    this.isEmail = false,
  });
@override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: TextFormField(
        decoration: InputDecoration(
          hintText: hintText,
          contentPadding: EdgeInsets.all(15.0),
          border: InputBorder.none,
          filled: true,
          fillColor: Colors.grey[200],
        ),
        obscureText: isPassword ? true : false,
        validator: validator,
        onSaved: onSaved,
        keyboardType: isEmail ? TextInputType.emailAddress : TextInputType.text,
      ),
    );
  }
}

这是具有所有变量的model.dart:
import 'package:flutter/material.dart';
import 'package:instaskool/screens/school_code.dart';

class Model {
  String fullname;
  String code;
  String standard;
  String section;
  String username;
  String password;
Model({this.fullname, this.code, this.standard, this.section, this.username, this.password});
}

class School {
  String schoolName;
  String schoolPhone;
  String schoolEmail;
  String schoolWebsite;
  School({this.schoolName, this.schoolPhone, this.schoolEmail, this.schoolWebsite});

}

class SchoolDet {
  String addressOne;
  String addressTwo;
  String city;
  String pincode;
  String state;

    SchoolDet({this.addressOne, this.addressTwo, this.city, this.pincode, this.state});

}

class SchoolUser{
  String username;
  String password;

  SchoolUser({this.username, this.password});
}

class SchoolCode{
  String principalCode;
  String teacherCode;
  String studentCode;

SchoolCode({this.principalCode, this.teacherCode, this.studentCode});
}

这是我想要显示所有数据的结果屏幕:-
import 'package:flutter/material.dart';
import 'package:instaskool/model.dart';

class ResultSchool extends StatelessWidget {
 School school;
 SchoolDet schooldet;
 SchoolCode schoolcode;
 SchoolUser schooluser;
 ResultSchool({this.school, this.schooldet, this.schooluser});
@override
  Widget build(BuildContext context) {
    return (Scaffold(
      appBar: AppBar(title: Text('School details')),
      body: Container(
        margin: EdgeInsets.all(10.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(school.schoolName, style: TextStyle(fontSize: 22)),
            Text(school.schoolPhone, style: TextStyle(fontSize: 22)),
            Text(school.schoolEmail, style: TextStyle(fontSize: 22)),
            Text(school.schoolWebsite, style: TextStyle(fontSize: 22)),
            Text(schooldet.addressOne, style: TextStyle(fontSize: 22)),
            Text(schooldet.addressTwo, style: TextStyle(fontSize: 22)),
            Text(schooldet.city, style: TextStyle(fontSize: 22)),
            Text(schooldet.pincode, style: TextStyle(fontSize: 22)),
            Text(schooldet.state, style: TextStyle(fontSize: 22)),

            Text(schooluser.username, style: TextStyle(fontSize: 22)),
            Text(schooluser.password, style: TextStyle(fontSize: 22)),

            Text(schoolcode.teacherCode, style: TextStyle(fontSize: 22)),
            Text(schoolcode.principalCode, style: TextStyle(fontSize: 22)),

          ],
        ),
      ),
    ));
  }
}

最佳答案

添加小部件以管理表单转换

enum SchoolFormPhase { BASIC_DTL, ADDRESS, USER_DTL }


class SchoolRegistration extends StatefulWidget {
  @override
  _SchoolRegistrationState createState() => _SchoolRegistrationState();
}

class _SchoolRegistrationState extends State<SchoolRegistration> {
  SchoolFormPhase phase;
  School schoolForm;

  @override
  void initState() {
    phase = SchoolFormPhase.BASIC_DTL;
    schoolForm = School();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    switch (phase) {
      case SchoolFormPhase.BASIC_DTL:
        return SchoolReg(
            school: schoolForm,
            onSaved: (school) {
              setState(() {
                schoolForm = school;
                phase = SchoolFormPhase.ADDRESS;
              });
            });

      case SchoolFormPhase.ADDRESS:
        return SchoolRegTwo(
            school: schoolForm,
            onSaved: (school) {
              setState(() {
                schoolForm = school;
                phase = SchoolFormPhase.USER_DTL;
              });
            });

      case SchoolFormPhase.USER_DTL:
        return SchoolRegThree(
          school: schoolForm,
          onSaved: (school) {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ResultSchool(
                        schooluser: school.user,
                        school: school,
                        schooldet: school.address)));
          },
        );
    }
    return Container();
  }
}

更改表单小部件以接受输入
class SchoolReg extends StatefulWidget {
  final School school;
  final Function(School) onSaved;

  const SchoolReg({Key key, this.school, this.onSaved}) : super(key: key);

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

class _SchoolRegState extends State<SchoolReg> {
  final _formKey = GlobalKey<FormState>();
  School _school;

  @override
  void initState() {
    _school = widget.school;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
            child: new Form(
                key: _formKey,
                child: Column(children: <Widget>[
                  Container(
                      margin: EdgeInsets.only(top: 130),
                      alignment: Alignment.topCenter,
                      child: MyTextFormField(
                          hintText: 'School name',
                          validator: (String value) {
                            return value.isEmpty
                                ? 'Enter your school name'
                                : null;
                          },
                          onSaved: (value) => _school.schoolName = value)),
                  MyTextFormField(
                    hintText: 'Phone',
                    validator: (String value) {
                      if (value.isEmpty) {
                        return 'Enter the phone number';
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      _school.schoolPhone = value;
                    },
                  ),
                  MyTextFormField(
                    hintText: 'Email',
                    validator: (String value) {
                      if (value.isEmpty) {
                        return 'Enter the email address';
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      _school.schoolEmail = value;
                    },
                  ),
                  MyTextFormField(
                    hintText: 'School Website',
                    isEmail: true,
                    validator: (String value) {
                      if (value.isEmpty) {
                        return "Enter the school's website";
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      _school.schoolWebsite = value;
                    },
                  ),
                  RaisedButton(
                      color: Colors.blueAccent,
                      onPressed: () {
                        if (_formKey.currentState.validate()) {
                          _formKey.currentState.save();
                          widget.onSaved(_school);
                        }
                      },
                      child:
                          Text('Next', style: TextStyle(color: Colors.white)))
                ]))));
  }
}

表格2
class SchoolRegTwo extends StatefulWidget {
  final School school;
  final Function(School) onSaved;

  const SchoolRegTwo({Key key, this.school, this.onSaved}) : super(key: key);

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

class _SchoolRegTwoState extends State<SchoolRegTwo> {
  final _formKey = GlobalKey<FormState>();
  SchoolDet schooldet;

  @override
  void initState() {
    schooldet = widget.school.address;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
            child: new Form(
                key: _formKey,
                child: Column(children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 130),
                    alignment: Alignment.topCenter,
                    child: MyTextFormField(
                      hintText: 'School address 1',
                      validator: (String value) {
                        if (value.isEmpty) {
                          return "Enter your school's address";
                        }

                        return null;
                      },
                      onSaved: (String value) {
                        schooldet.addressOne = value;
                      },
                    ),
                  ),
                  MyTextFormField(
                    hintText: 'School address 2',
                    validator: (String value) {
                      if (value.isEmpty) {
                        return "Enter the school's address";
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      schooldet.addressTwo = value;
                    },
                  ),
                  MyTextFormField(
                    hintText: 'City',
                    validator: (String value) {
                      if (value.isEmpty) {
                        return 'Enter the city';
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      schooldet.city = value;
                    },
                  ),
                  MyTextFormField(
                    hintText: 'Pincode',
                    isEmail: true,
                    validator: (String value) {
                      if (value.isEmpty) {
                        return "Enter the pincode";
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      schooldet.pincode = value;
                    },
                  ),
                  MyTextFormField(
                    hintText: 'State',
                    isEmail: true,
                    validator: (String value) {
                      if (value.isEmpty) {
                        return "Enter the state";
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      schooldet.state = value;
                    },
                  ),
                  RaisedButton(
                      color: Colors.blueAccent,
                      onPressed: () {
                        if (_formKey.currentState.validate()) {
                          _formKey.currentState.save();
                          widget.school.address = schooldet;
                          widget.onSaved(widget.school);
                        }
                      },
                      child:
                          Text('Next', style: TextStyle(color: Colors.white)))
                ]))));
  }
}

表格3
class SchoolRegThree extends StatefulWidget {
  School school;
  final Function(School) onSaved;

  SchoolRegThree({this.school, this.onSaved});

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

class _SchoolRegThreeState extends State<SchoolRegThree> {
  final _formKey = GlobalKey<FormState>();
  SchoolUser schooluser;

  @override
  void initState() {
    schooluser = widget.school.user;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
            child: new Form(
                key: _formKey,
                child: Column(children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 100),
                    child: MyTextFormField(
                      hintText: 'Username',
                      isPassword: true,
                      validator: (String value) {
                        if (value.length < 5) {
                          return 'Username should be at least 5 characters long';
                        }

                        _formKey.currentState.save();

                        return null;
                      },
                      onSaved: (String value) {
                        schooluser.username = value;
                      },
                    ),
                  ),
                  MyTextFormField(
                    hintText: 'New Password',
                    isPassword: true,
                    validator: (String value) {
                      if (value.length < 7) {
                        return 'Password should be at least 7 characters long';
                      } else if (schooluser.password != null) {
                        print(value);

                        print(schooluser.password);
                      }

                      return null;
                    },
                    onSaved: (String value) {
                      schooluser.password = value;
                    },
                  ),
                  RaisedButton(
                      color: Colors.blueAccent,
                      onPressed: () {
                        if (_formKey.currentState.validate()) {
                          _formKey.currentState.save();
                          widget.school.user = schooluser;
                          widget.onSaved(widget.school);
                        }
                      },
                      child: Text('Done',
                          style: TextStyle(
                            color: Colors.white,
                          )))
                ]))));
  }
}

最后将模型合并为一个模型类
class School {
  String schoolName;
  String schoolPhone;
  String schoolEmail;
  String schoolWebsite;
  SchoolDet address;
  SchoolUser user;
}

class SchoolDet {
  String addressOne;
  String addressTwo;
  String city;
  String pincode;
  String state;
}

class SchoolUser {
  String username;
  String password;
}

关于flutter - 如何将数据从表单传递到下一个屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61931162/

相关文章:

dart - 如何在flutter中的TextFormField中实现日期逻辑

flutter - 在 ListView 中使用CachedVideoPlayer

iframe - 如何在Dart中从iframe接收数据?

flutter - 为什么在容器中的图像后面有形状?

flutter - flutter 柱删除空间之间的子项

flutter - 返回 map 时,FutureBuilder中的空快照

flutter - 如何在提交时将文本字段更改为另一个小部件?

flutter - Android studio无法识别flutter类AppBar?

flutter - 什么时候应该在 Dart/Flutter 中使用分号?

flutter - 错误 应为类型 '(() => void)?' 的值,但得到类型 '+Future<dynamic>' 之一