【问题标题】:How to pass the data from the form to the next screen in flutter?如何在颤动中将数据从表单传递到下一个屏幕?
【发布时间】:2020-05-21 09:15:57
【问题描述】:

我正在构建一个包含大量文本字段的很长表单的应用程序,因此我将文本字段划分为多个屏幕。它有三个屏幕,第一个屏幕有一些常见的文本字段,如电话、网站、电子邮件等。第二个屏幕有更多的文本字段,与第三个屏幕相同。我正在尝试在不同的屏幕上显示最后三个表单中的所有详细信息。

当我点击不同页面上的“完成”按钮时,我想在最后显示所有详细信息。

这是第一个屏幕的代码:-

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)),

          ],
        ),
      ),
    ));
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    添加一个小部件来管理表单转换

    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;
    }
    

    【讨论】:

    • 如何更改按钮点击中的表单?
    • 请有人帮我解决这个问题!
    • 我已经提到了整个事情的代码,有人可以看看这个并告诉我如何解决这个问题吗?
    • 非常感谢@Nidheesh 调查此事,我真的很感激。我只想问你是如何掌握java和dart的。我是一名 python 开发人员,我真的很喜欢它,我正在尝试进入 java 和 dart。我想尽快和你谈谈。谢谢
    • 我来自java,很容易适应flutter
    【解决方案2】:

    最好使用flutter_bloc、provider等状态管理解决方案

    使用状态管理将其存储在不同文件的数组中。

    使 bloc/provider 可用于所有屏幕。

    你可以通过构造函数,但我不建议这样做,因为它会太乱。

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2023-01-23
      • 2019-09-21
      • 2019-11-17
      • 2020-07-26
      • 1970-01-01
      • 2023-01-11
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多