简体   繁体   English

将快照数据从一个 dart 文件传递到 flutter 项目中的另一个文件

[英]Pass Snapshot Data from One dart file to another in flutter project

In my flutter project their are 2 dart files.在我的 flutter 项目中,它们是 2 个 dart 文件。 In the 1st dart page their is an initstate func that fetches snapshot data from firebase database[from line 19 onwards].在第一个 dart 页面中,它们是一个 initstate 函数,它从 firebase 数据库中获取快照数据[从第 19 行开始]。 The first page is further routes to the second page[at line 71].第一页是到第二页的进一步路由[在第 71 行]。 While routing it must also send the snapshot data to the 2nd dart page.在路由时,它还必须将快照数据发送到第二个 dart 页面。 In the second page the data is extracted from snapshot and used as initial value of the TextField in the 2nd dart page.在第二页中,从快照中提取数据并用作第二个 dart 页面中 TextField 的初始值。 Here is the code of both the dart file.这是 dart 文件的代码。

1st dart file:第一个 dart 文件:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:udharibook/Screens/UserProfile.dart';
import 'package:udharibook/services/authservice.dart';
import 'Customer_Support.dart';

class DashboardPage extends StatefulWidget {
  @override
  _DashboardPageState createState() => _DashboardPageState();
}

class _DashboardPageState extends State<DashboardPage> {

  String userName;
  @override
  void initState()
  {
    super.initState();
    FirebaseAuth _auth = FirebaseAuth.instance;
    DatabaseReference DBRef = FirebaseDatabase.instance.reference().child('Users');
    _auth.currentUser().then((curUser){
      DBRef.child(curUser.uid).once().then((DataSnapshot user){
        userName = user.value['Name'];
        setState(() {
          print('Username is:'+userName);
        });
      });
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('$userName'),
        backgroundColor: Color.fromRGBO(162, 42, 43, 1.0),
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.search),
              onPressed: () {
                print("Search Clicked");
              }),
          IconButton(
              icon: Icon(Icons.sort),
              onPressed: () {
                print("Sort Clicked");
              }),
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            DrawerHeader(
              child: Text('$userName'),
              decoration: BoxDecoration(
                color: Color.fromRGBO(162, 42, 43, 1.0),
              ),
            ),
            CustomMenu(
                Icons.person,
                'Profile',() => {

                      Navigator.pop(context),
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => UserProfile()))
                    }),
            CustomMenu(Icons.assessment, 'Reports', () => {}),
            CustomMenu(Icons.settings, 'Settings', () => {}),
            CustomMenu(
                Icons.perm_phone_msg,
                'Customer Support',
                () => {
                      Navigator.pop(context),
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => CustSupport()))
                    }),
            CustomMenu(Icons.lock, 'Log Out', () => {AuthService().signOut()}),
          ],
        ),
      ),
    );
  }
}

class CustomMenu extends StatelessWidget {
  IconData icon;
  String text;
  Function onTap;

  CustomMenu(this.icon, this.text, this.onTap);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Padding(
        padding: EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 0.0),
        child: Container(
            decoration: BoxDecoration(
                border:
                    Border(bottom: BorderSide(color: Colors.grey.shade400))),
            child: InkWell(
                splashColor: Colors.redAccent,
                onTap: onTap,
                child: Container(
                  height: 60.0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Icon(icon),
                          Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Text(
                                text,
                                style: TextStyle(
                                    fontSize: 17.0, fontFamily: 'Exo2'),
                              )),
                        ],
                      ),
                      Icon(Icons.arrow_right),
                    ],
                  ),
                ))));
  }
}

2nd Dart file:第二个 Dart 文件:

import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart';

class UserProfile extends StatefulWidget {
  @override
  _UserProfileState createState() => _UserProfileState();
}
class _UserProfileState extends State<UserProfile> {
  File _image;
  TextEditingController nameController = TextEditingController(text: 'abc');
  TextEditingController mobileController = TextEditingController(text: '88888888');
  TextEditingController emailController =TextEditingController()..text='abc@gmail.com';
  TextEditingController addressController =TextEditingController()..text='India';

  @override
  Widget build(BuildContext context) {

    Future getImage() async{
      var image=await ImagePicker.pickImage(source: ImageSource.gallery);

      setState(() {
        _image=image;
        print('Image Path $_image');
      });
    }

    Future uploadPic(BuildContext context) async{

      String fileName = basename(_image.path);
      StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
      StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
      StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
      setState(() {
        print("Profile Picture Uploaded");
        Scaffold.of(context).showSnackBar(SnackBar(content:Text('Profile Updated')));
      });
    }
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: Text('User Profile'),
        backgroundColor: Color.fromRGBO(162, 42, 43, 1.0),
      ),
      body: Builder(
        builder: (context) => Container(
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 20.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Align(
                    alignment: Alignment.center,
                    child: CircleAvatar(
                      radius: 70,
                      backgroundColor: Colors.white,
                      child: ClipOval(
                        child: SizedBox(
                            height: 120.0,
                            width:120.0,
                            child:_image!=null?Image.file(_image,fit: BoxFit.fill):
                            Image.network(
                              'https://firebasestorage.googleapis.com/v0/b/udhari-book.appspot.com/o/DefaultImage.png?alt=media&token=06bddd3e-7f11-476b-a982-dfb21096f9c7',
                              fit: BoxFit.fitWidth,
                            ),
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only( ),
                    child: IconButton(
                        icon: Icon(Icons.camera_alt), onPressed: () {
                          getImage();
                    }),
                  )
                ],
              ),
              Padding(
                  padding: EdgeInsets.only(top:20.0,left: 10.0,right: 10.0),
                  child:SizedBox(
                    height: 40.0,
                  child: TextField(
                    controller: nameController,
                    decoration: InputDecoration(
                        labelText: 'Full Name',
                        labelStyle:
                            TextStyle(fontFamily: 'Exo2', color: Colors.grey),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0)
                        ),
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5.0),
                            borderSide: BorderSide(
                                color:
                                Color.fromRGBO(162, 42, 43, 1.0)
                            )

                        )
                    ),
                  ),
              )),
              Padding(
                padding: EdgeInsets.only(top:15.0,left: 10.0,right: 10.0),
                child:SizedBox(
                  height: 40.0,
                child: TextField(
                  controller: mobileController,
                  enabled: false,
                  keyboardType:TextInputType.phone,
                  decoration: InputDecoration(
                      labelText: 'Mobile Number',
                      labelStyle:
                      TextStyle(fontFamily: 'Exo2', color: Colors.grey),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0)),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0),
                          borderSide: BorderSide(
                              color:
                              Color.fromRGBO(162, 42, 43, 1.0)
                          )
                      )
                  ),
                ),
              )),
              Padding(
                padding: EdgeInsets.only(top:15.0,left: 10.0,right: 10.0),
                child:SizedBox(
                  height: 40.0,
                child: TextField(
                  controller: emailController,
                  keyboardType: TextInputType.emailAddress,
                  decoration: InputDecoration(
                      labelText: 'Email (Optional)',
                      labelStyle:
                      TextStyle(fontFamily: 'Exo2', color: Colors.grey),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(5.0)
                      ),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0),
                          borderSide: BorderSide(
                              color:
                              Color.fromRGBO(162, 42, 43, 1.0)
                          )

                      )
                  ),
                ),
              )),
              Padding(
                padding: EdgeInsets.only(top:15.0,left: 10.0,right: 10.0,bottom: 30.0),
                child: TextField(
                  maxLines: 3,
                  maxLengthEnforced: true,
                  controller: addressController,
                  keyboardType: TextInputType.emailAddress,
                  decoration: InputDecoration(
                      labelText: 'Address (Optional)',
                      labelStyle:
                      TextStyle(fontFamily: 'Exo2', color: Colors.grey),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0)
                      ),
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0),
                          borderSide: BorderSide(
                              color:
                              Color.fromRGBO(162, 42, 43, 1.0)
                          )
                      )
                  ),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  SizedBox(
                    width:130.0,
                  height: 50.0,
                  child:RaisedButton(
                    color: Color.fromRGBO(162, 42, 43, 1.0),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(18.0)
                    ),
                    onPressed: (){
                      uploadPic(context);
                      //readUSerData();
                      Navigator.of(context).pop();
                    },
                    elevation: 4.0,
                    splashColor: Colors.blueGrey,
                    child: Text(
                      'Save',
                      style: TextStyle(
                        color:Colors.white,fontSize: 22.0,fontFamily: 'Exo2'
                      ),
                    ),
                  )),
                  SizedBox(
                    width:130.0,
                  height:50.0,
                  child:RaisedButton(
                    color: Color.fromRGBO(162, 42, 43, 1.0),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(18.0)
                    ),
                    onPressed: (){
                      Navigator.of(context).pop();
                    },
                    elevation: 4.0,
                    splashColor: Colors.blueGrey,
                    child: Text(
                      'Cancel',
                      style: TextStyle(
                          color:Colors.white,fontSize: 22.0,fontFamily: 'Exo2'
                      ),
                    ),
                  ))
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

You can create a constructor for your second page that takes in the data you need.你可以为你的第二个页面创建一个构造函数来接收你需要的数据。 You then pass that data into the page when you call the Navigator eg然后在调用导航器时将该数据传递到页面中,例如

class UserProfile extends StatefulWidget {

  final String username;

  const UserProfile({Key key, this.username}) : super(key: key);

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

Then in your first page when navigating you call:然后在导航时在您的第一页中调用:

Navigator.push(context, MaterialPageRoute(builder: 
    (context) => UserProfile(username: userName)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM