【问题标题】:Display Cloud Firebase data? [closed]显示 Cloud Firebase 数据? [关闭]
【发布时间】:2021-01-10 18:53:32
【问题描述】:

嘿,有谁知道我如何从我的 Cloud Firebase 中显示这个变量 url? 如果有人能做一个巨大的例子,那就太好了! :)

class EditProfile extends StatefulWidget {
  @override
  _EditProfileState createState() => _EditProfileState();
}

class _EditProfileState extends State<EditProfile> {

  FocusNode myFocusNode1 = new FocusNode();
  FocusNode myFocusNode3 = new FocusNode();





  final _formkey = GlobalKey<FormState>();
  String _UserName ;
  String _Email ;
  String _URL;
  File _image;



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

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

  Future<DocumentSnapshot> getUserInfo() async {
    var firebaseUser = await FirebaseAuth.instance.currentUser;
    return await FirebaseFirestore.instance.collection("SerX")
        .doc(firebaseUser.uid)
        .get();
  }

  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;
    var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
    _URL = downUrl.toString();

    

    setState(() async {
      print('Profile Picture uploaded');
      var firebaseUser = await FirebaseAuth.instance.currentUser;
      FirebaseFirestore.instance.collection("SerX").doc(firebaseUser.uid).update({"url" : downUrl});
      Scaffold.of(context).showSnackBar(
          SnackBar(content: Text('Profile Picture Uploaded')));
    });
  }




  @override
  void dispose() {
   myFocusNode1 = FocusNode();
   myFocusNode3 = FocusNode();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {



    myFocusNode1.addListener(() {setState(() {

    }); });
    myFocusNode3.addListener(() {setState(() {

    }); });

    final user = Provider.of<Userf>(context);


    return  StreamBuilder<UserData>(
      stream: DatabaseService(uid: user.uid).userData,
      builder: (context, snapshot) {
        if(snapshot.hasData){
         UserData userData = snapshot.data;
          return Form(
            key: _formkey,
            child: Scaffold(
              appBar: AppBar(
                bottom: PreferredSize(
                    child: Container(
                      color: Colors.blue,
                      height: 4.0,
                    ),
                    preferredSize: Size.fromHeight(0)),
                backgroundColor: Colors.black,
                leading: IconButton(icon: Icon(Icons.arrow_back ,color: Colors.blue,),onPressed: (){
                  Navigator.pushReplacement(context,
                      MaterialPageRoute(builder: (context) => HomeScreen()));
                },),
                title: Text('Profile', style: TextStyle(
                  color:Colors.white,
                  fontSize: 25,
                  fontWeight: FontWeight.bold,
                  fontFamily: 'Orbitron',
                ),
                  textAlign: TextAlign.center,
                ),
              ),
              body: Container(
                  color: Colors.black,
                  child: ListView(
                    children: [
                      Stack(
                        children: [
                          Container(
                            margin: EdgeInsets.fromLTRB(140,45,0,0),
                            width: 130,
                            height: 130,
                            decoration: BoxDecoration(
                                border: Border.all(
                                  width: 3,
                                  color: Colors.blue,
                                ),
                                boxShadow: [BoxShadow(
                                  spreadRadius: 2, blurRadius: 10,
                                  color: Colors.white.withOpacity(0.1),
                                  offset: Offset(0,10),
                                ),
                                ],
                                shape: BoxShape.circle,
                                image: DecorationImage(
                                  fit: BoxFit.cover,
                                  image: (_image != null) ? FileImage(
                                      _image)
                                      : NetworkImage(_URL.toString()),
                                )
                            ),
                          ),
                          Positioned(
                            bottom: 0,
                            right: 150,
                            child: Container(
                              height: 35,
                              width: 35,
                              decoration: BoxDecoration(
                                border: Border.all(width: 2, color: Colors.blue),
                                shape: BoxShape.circle,
                                color: Colors.white,
                              ),
                              child: IconButton(icon: Icon(Icons.edit), color: Colors.blue,iconSize:
                                17, onPressed: () async {
                                getImage(context);
                              },),
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 40),

                      TextFormField(
                        initialValue: userData.Username,
                        onChanged: (val) => setState(() => _UserName = val),
                        validator: (input){
                          if (input.isEmpty) {
                            return 'Please enter a username';
                          }

                          if(input.length < 6){
                            return 'Your username needs to be at least 6 characters';
                          }else if(input.length > 12){
                            return 'Your username needs to be at most 12 characters';
                          }

                          if (!RegExp(
                              r'^[a-zA-Z0-9]+$')
                              .hasMatch(input)) {
                            return 'a-z, A-Z, 0-9';
                          }

                        },
                        focusNode: myFocusNode1,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'Orbitron',
                        ),
                        decoration: InputDecoration(
                          focusedBorder: OutlineInputBorder(
                            borderSide: const BorderSide(color: Colors.blue, width: 1.0),
                            borderRadius: BorderRadius.circular(25.0),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: const BorderSide(color: Colors.white, width: 1.0),
                            borderRadius: BorderRadius.circular(25.0),
                          ),
                          icon: Icon(Icons.edit, color: Colors.blue,),
                          contentPadding: EdgeInsets.only(bottom: 3),
                          labelText: "Username",
                          labelStyle: TextStyle(color: myFocusNode1.hasFocus ? Colors.blue : Colors.white),
                          floatingLabelBehavior: FloatingLabelBehavior.always,
                          prefixIcon: myFocusNode1.hasFocus ? Icon(Icons.account_circle, color: Colors.blue,): Icon(Icons.account_circle, color: Colors.white,),
                          hintStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'Orbitron',
                          ),
                        ),
                      ),
                      SizedBox(height: 35),
                      Row(
                        children: [
                          SizedBox(width: 40,),
                          RaisedButton(
                            onPressed: (){
                              Navigator.pushReplacement(context, MaterialPageRoute(
                                  builder: (context) => HomeScreen()));
                            },
                            color: Colors.white,
                            padding: EdgeInsets.symmetric(horizontal: 10),
                            shape: RoundedRectangleBorder(borderRadius:  BorderRadius.circular(20)),
                            elevation: 2,
                            child: Text("CANCEL",
                              style:TextStyle(
                                color: Colors.black,
                                fontSize: 25,
                                fontWeight: FontWeight.bold,
                                fontFamily: 'Orbitron',
                                letterSpacing: 2.2,
                              ),),
                          ),
                          SizedBox(width: 30,),
                          RaisedButton(
                            onPressed: () async{
                             if(_formkey.currentState.validate()){
                               await DatabaseService(uid: user.uid).updateUserData(
                                   _UserName ?? userData.Username,
                               _Email ?? userData.Email,
                                   _URL ?? userData.URL);
                               Navigator.pushReplacement(context, MaterialPageRoute(
                               builder: (context) => LoadingUpdate()));
                             }
                            },
                            color: Colors.blue,
                            padding: EdgeInsets.symmetric(horizontal: 30),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                            elevation: 2,
                            child: Text("SAVE" ,style:TextStyle(
                              color: Colors.black,
                              fontSize: 27,
                              fontWeight: FontWeight.bold,
                              fontFamily: 'Orbitron',
                              letterSpacing: 2.2,
                            ),),
                          )
                        ],
                      ),
                    ],
                  )
              ),
            ),
          );
        }else{
          return Center(
              child: SpinKitFadingCircle(color: Colors.white, size: 20.0),
        heightFactor: 29,
          );
        }

      }
    );
  }
}



BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border.all(
      color: Colors.blue, //                   <--- border color
      width: 5.0,
    ),
  );

dnkjcnsjkndkcnsjkcnkjsndckjnsdkjcnsjkdcnkjnsdkcjnsd skcnkjsndcknsdkjcnkjsdcnkjnsdjkcnsjkdcnjknsdc scdhbsdjbcjhsdbcjhbsdhjcbsjhdcbhjdbsjdbcjhsbdc scjbsdjhcsjdcbjhsdbcjhbsdc

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:
    final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
    
    try {
            DocumentSnapshot document = await _firestore
                .collection('SerX')
                .doc(documentID) //replace with the document id
                .get();
            Map<String, dynamic> json = document.data() // your data 
            // for example to get the email value -> json["Email"]
          } catch (e) {
            throw Exception();
          }
    

    【讨论】:

    • json??这也适合颤振
    • 是的,在颤动中,json 通常是 Map 类型的 json。但你可以随意调用它
    • 好的,但是我怎样才能在这里显示它:
    • 图像:(_image!= null)? FileImage(_image) : NetworkImage(_URL.toString()),
    • 对于这样的网址: Map json = document.data();打印(json[“url”]);为了显示图像,请使用小部件 NetworkImage(json["url"]);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2017-07-13
    • 2019-01-15
    • 1970-01-01
    • 2021-09-26
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多