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

Posted

技术标签:

【中文标题】将快照数据从一个 dart 文件传递​​到颤振项目中的另一个文件【英文标题】:Pass Snapshot Data from One dart file to another in flutter project 【发布时间】:2020-10-24 18:28:51 【问题描述】:

在我的颤振项目中,它们是 2 个 dart 文件。 在第一个 dart 页面中,它们是一个 initstate 函数,它从 firebase 数据库中获取快照数据[从第 19 行开始]。第一页是到第二页的进一步路由[在第 71 行]。在路由时,它还必须将快照数据发送到第二个 dart 页面。在第二页中,从快照中提取数据并用作第二页中 TextField 的初始值。 这是两个 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),
                    ],
                  ),
                ))));
  

第二个 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'
                      ),
                    ),
                  ))
                ],
              )
            ],
          ),
        ),
      ),
    );
  

【问题讨论】:

【参考方案1】:

你可以为你的第二个页面创建一个构造函数来接收你需要的数据。然后在调用 Navigator 时将该数据传递到页面中,例如

class UserProfile extends StatefulWidget 

  final String username;

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

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

然后在你的第一页导航时调用:

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

【讨论】:

以上是关于将快照数据从一个 dart 文件传递​​到颤振项目中的另一个文件的主要内容,如果未能解决你的问题,请参考以下文章

颤振使用路由将数组数据从一个屏幕传递到另一个屏幕

Dart:如何通过流将数据从一个进程传递到另一个进程

如何将快照数据从 futurebuilder 传递到同一页面中的另一个 futurebuilder?

如何在不创建新的 dart 项目的情况下运行与我的颤振项目隔离的 dart 代码?

将 API 数据从第 1 页传递到 Flutter 上的另一个 dart 页面

通过方法通道颤振传递自定义对象