簡體   English   中英

如何將表單中的數據傳遞到 flutter 中的下一個屏幕?

[英]How to pass the data from the form to the next screen in flutter?

我正在構建一個包含很多文本字段的很長表單的應用程序,因此我將文本字段划分為多個屏幕。 它有三個屏幕,第一個屏幕有一些常見的文本字段,例如電話、網站、email 等。第二個屏幕有更多的文本字段,與第三個屏幕相同。 我試圖在不同的屏幕上顯示最后三個 forms 的所有詳細信息。

第一個屏幕

在此處輸入圖像描述

在此處輸入圖像描述

當我點擊不同頁面上的“完成”按鈕時,我想最后顯示所有詳細信息。

這是具有第一種形式的第一個屏幕的代碼:-

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,
                          )))
                ]))));
  }
}

最后將 model 合並為單個 model class

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

最好是使用 state 管理解決方案,如 flutter_bloc、provider 等。

使用 state 管理將其存儲在不同文件的數組中。

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

您可以通過構造函數,但我不建議這樣做,因為它會太亂。

暫無
暫無

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

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