简体   繁体   English

如何在没有上下文的情况下使用提供者?

[英]How can I use provider without context?

I have a widget where I use the provider but where I want to use the values is in normal widgets so maybe anyone can help.我有一个小部件,我在其中使用提供程序,但我想在普通小部件中使用这些值,所以也许任何人都可以提供帮助。

This is where I use the provider:这是我使用提供程序的地方:


  Widget _buildName(BuildContext context) {
    return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              'Full Name',
              style: kLabelStyle3,
            ),
            SizedBox(height: 10.0),
            Container(
              alignment: Alignment.centerLeft,
              height: 50.0,
              child: TextFormField(
                initialValue: UserData.fullname;
                validator: (val) => val.isEmpty ? 'Enter your Name' : null,
                onChanged: (val) {
                  setState(() => _currentfullname = val);
                },
                style: TextStyle(
                  color: Colors.black,
                  fontFamily: 'OpenSans',
                ),
                decoration: InputDecoration(
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    borderSide: BorderSide(
                      color: Colors.black,
                      width: 2.0,
                    ),
                  ),
                  contentPadding: EdgeInsets.only(top: 14.0),
                  prefixIcon: Icon(
                    Icons.person,
                    color: Colors.black,
                  ),
                  hintText: 'Enter your Name',
                  hintStyle: kHintTextStyle2,
                ),
              ),
            ),
          ],
        );

  }

  @override
  Widget build(BuildContext context) {
final user = Provider.of<Userr>(context);
        return StreamBuilder<UserData>(
          stream: DatbaseService(uid:user.uid).userData,
          builder: (context, snapshot) {
            if(snapshot.hasData){
              UserData userData =snapshot.data;
              return Scaffold(
                appBar: AppBar(
                  backgroundColor: Colors.transparent,
                  elevation: 0.0,
                ),
                body: AnnotatedRegion<SystemUiOverlayStyle>(
                  value: SystemUiOverlayStyle.light,
                  child: GestureDetector(
                    onTap: () => FocusScope.of(context).unfocus(),
                    child: Form(
                      key: _formKey,
                      child: Stack(
                        children: <Widget>[
                          Container(
                            height: double.infinity,
                            child: SingleChildScrollView(
                              physics: AlwaysScrollableScrollPhysics(),
                              padding: EdgeInsets.symmetric(
                                horizontal: 40.0,
                                vertical: 10,
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Center(
                                    child: Stack(
                                      children: [
                                        Container(
                                          width: 110,
                                          height: 110,
                                          decoration: BoxDecoration(

                                              borderRadius: BorderRadius.circular(100),
                                              image: DecorationImage(
                                                  fit: BoxFit.cover,
                                                  image: NetworkImage(
                                                    "https://images.pexels.com/photos/3307758/pexels-photo-3307758.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=250",
                                                  ))),
                                        ),
                                        Positioned(
                                            bottom: 0,
                                            right: 0,
                                            child: Container(
                                              height: 35,
                                              width: 35,
                                              decoration: BoxDecoration(
                                                shape: BoxShape.circle,
                                                border: Border.all(
                                                  width: 4,
                                                  color: Theme.of(context)
                                                      .scaffoldBackgroundColor,
                                                ),
                                                color: Colors.green,
                                              ),
                                              child: Icon(
                                                Icons.edit,
                                                color: Colors.white,
                                              ),
                                            )),
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Text(
                                    'Mein Profil',
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontFamily: 'OpenSans',
                                      fontSize: 20.0,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  showAlert2(),

                                    _buildEmailTF(),
                                  SizedBox(
                                    height: 30.0,
                                  ),
                                  _buildName(),
                                  SizedBox(
                                    height: 30.0,
                                  ),
                                  _builduserName(),
                                  SizedBox(
                                    height: 30.0,
                                  ),
                                  _buildPasswordTF(),
                                  SizedBox(height: 30,),

                                  _buildPassword2TF(),
                                  _buildUpdateDataButton(),
                                  // _buildEmailform(),
                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),

              );

            }else{
return null;
            }


          }
        );


      }



  }


class DatbaseService{

  final String uid;
  DatbaseService({this.uid});
  //collection reference
  final CollectionReference myprofilsettings = FirebaseFirestore.instance.collection('meinprofilsettings');

  Future updateUserData(String user,String fullname,String password,String email)async{
    return await myprofilsettings.doc(uid).set({
      'username':user,
      'fullname':fullname,
      'passwort':password,
      'email':email,
    });

  }

  //profil list from snapshot
  List<myprofil> _myprofillistFromSnapshot(QuerySnapshot snapshot){
    return snapshot.docs.map((doc){
      return myprofil(
        user: doc.data()['user']??'',
        fullname: doc.data()['fullname']??'',
        email: doc.data()['email']??'',
        passowrd: doc.data()['password']??'',


      );
    }).toList();
  }
  //userData from snapshot
  UserData _userDataFromSnapshot(DocumentSnapshot snapshot){
    return UserData(
      uid: uid,
      name: snapshot.data()['name'],
      fullname: snapshot.data()['fullname'],
      email: snapshot.data()['email'],
      password: snapshot.data()['password'],


    );
  }
  //get myprofilsettings stream
  Stream<List<myprofil>> get settings{
    return myprofilsettings.snapshots().map(_myprofillistFromSnapshot);
  }

  //get user doc stream
Stream<UserData> get userData{
    return myprofilsettings.doc(uid).snapshots().map(_userDataFromSnapshot);
}
}


import 'package:flutter/cupertino.dart';

class Userr{

  final String uid;

  Userr({this.uid});



}
class UserData {
  final String uid;
  final String user;
  final String fullname;
  final String email;
  final String passowrd;

  UserData({this.uid,this.user,this.fullname,this.email,this.passowrd, name, password});


Ignore this: Because flutter says __it looks like It looks like your post is mostly code;忽略这一点:因为 flutter 说 __it looks like 看起来您的帖子主要是代码; please add some more details.请添加更多细节。 ___ IM adding some textdehpkfnwrfemrjfikerfoiwnfdoiwjefiojnweoidfjwiodjwiojdoijweiodjweiojdoiewjdijewoijdoejwdiojewiojdiowjedijweoidjiowediwjdoiwejdiowjdiojwoidjaldknjlncjnnc xy,,y,y,,y,ykampkdnndendiowendiojweiopjdipqejkdpojkdposkqwpodkqopwkdopkqwopdskqopdkpoqwkdopqkwopdkqwpodkpoqkdpkqpodkpqkdpokdpo<skcpoaskdpoakdopkdpoekwopdkwepokdpowekdpokwepodkwepokdpowekdpowekpdkpekdpokeopdkpekdpowekdopewkpdkwpekdpwekdpowekdpowekdpowekdpkwepodkwepodkpoekdpoewkdpoekdp ___ IM adding some textdehpkfnwrfemrjfikerfoiwnfdoiwjefiojnweoidfjwiodjwiojdoijweiodjweiojdoiewjdijewoijdoejwdiojewiojdiowjedijweoidjiowediwjdoiwejdiowjdiojwoidjaldknjlncjnnc xy,,y,y,,y,ykampkdnndendiowendiojweiopjdipqejkdpojkdposkqwpodkqopwkdopkqwopdskqopdkpoqwkdopqkwopdkqwpodkpoqkdpkqpodkpqkdpokdpo<skcpoaskdpoakdopkdpoekwopdkwepokdpowekdpokwepodkwepokdpowekdpowekpdkpekdpokeopdkpekdpowekdopewkpdkwpekdpwekdpowekdpowekdpowekdpkwepodkwepodkpoekdpoewkdpoekdp

======== Exception caught by widgets library =======================================================
The following assertion was thrown building StreamBuilder<UserData>(dirty, state: _StreamBuilderBaseState<UserData, AsyncSnapshot<UserData>>#c612d):
A build function returned null.

The offending widget is: StreamBuilder<UserData>
Build functions must never return null.

To return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".

The relevant error-causing widget was: 
  StreamBuilder<UserData> file:///Users/name/StudioProjects/project/lib/seitenleiste/meinacount.dart:356:16
When the exception was thrown, this was the stack: 
#0      debugWidgetBuilderValue.<anonymous closure> (package:flutter/src/widgets/debug.dart:305:7)
#1      debugWidgetBuilderValue (package:flutter/src/widgets/debug.dart:326:4)
#2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4592:7)
#3      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4759:11)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================

I'm assuming that your _buildName() is a method of your widget and that you call it from you build method somewhere.我假设您的_buildName()是您的小部件的一种方法,并且您从某处的构建方法中调用它。

This means that you can pass either the context or the user into this method: _buildName(BuildContext context) {} or _buildName(User user) {}这意味着您可以将上下文或用户传递到此方法中: _buildName(BuildContext context) {}_buildName(User user) {}

Try providing more of the code next time, specifically the parts where you call the method.下次尝试提供更多代码,特别是调用方法的部分。

Edit after post update:发布更新后编辑:

You need to have the user object in the buildName method so you cannot simply do UserData.fullname because UserData is a class not an instance.您需要在 buildName 方法中拥有用户 object ,因此您不能简单地执行UserData.fullname因为UserData是 class 而不是实例。

So to get your data in the buildName you need to change it to:因此,要在 buildName 中获取数据,您需要将其更改为:

_buildName(UserData userData) {
  userData.fullname; // this now exists
}

And call is like: _buildName(userData)调用就像: _buildName(userData)

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

相关问题 如何通过 openID 提供程序使用 Firebase 自定义身份验证? - How can I use Firebase custom auth with an openID provider? 如何将Firebase SSL证书与单独的DNS提供商一起使用 - How can I use a Firebase SSL Certificate with a separate DNS provider 如何使用 observables 来更新上下文提供者以用于提供者组件(React/Firebase)? - How to use observables to update a context provider for purposes of a Provider component (React/Firebase)? 没有模拟器怎么用firebase? - How can I use firebase without the emulator? 如何初始化OnFragmentInteractionListener而不使用onAttach(上下文上下文)以与FirebaseUI一起使用 - How to initialize OnFragmentInteractionListener without onAttach(Context context) for use with FirebaseUI 如果我无法获得上下文信息,该如何使用Picaso? - If i can't get context how can i use like Picaso? 如何验证提供商(Google或Facebook)是否已经使用了电子邮件地址? - How can I verify if an email address is already use by a provider (Google or Facebook)? 如何使用提供者? - How to use provider? 如何在没有谷歌帐户的情况下使用 Firebase 应用分发? - How can i use Firebase App distribution without google account? 如何在不更改先前字符串的情况下使用拆分字符串 - How can I use split the string without changing previous string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM