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

Posted

技术标签:

【中文标题】如何在没有上下文的情况下使用提供者?【英文标题】:How can I use provider without context? 【发布时间】:2021-06-09 20:17:18 【问题描述】:

我有一个小部件,我在其中使用提供程序,但我想在普通小部件中使用值,所以也许任何人都可以提供帮助。

这是我使用提供者的地方:


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


忽略这个: 因为颤振说 __it 看起来像它看起来你的帖子主要是代码;请添加更多细节。 ___ IM加入一些textdehpkfnwrfemrjfikerfoiwnfdoiwjefiojnweoidfjwiodjwiojdoijweiodjweiojdoiewjdijewoijdoejwdiojewiojdiowjedijweoidjiowediwjdoiwejdiowjdiojwoidjaldknjlncjnnc XY ,, Y,Y ,, Y,ykampkdnndendiowendiojweiopjdipqejkdpojkdposkqwpodkqopwkdopkqwopdskqopdkpoqwkdopqkwopdkqwpodkpoqkdpkqpodkpqkdpokdpo

======== 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)
...
====================================================================================================

【问题讨论】:

没有 BuildContext 就不能使用 Provider。考虑改用riverpod.dev。我希望这个答案对您有所帮助,因为这个问题实际上还不够清楚。 嗯,你真的不能在我的代码上展示如何做到这一点...... 【参考方案1】:

我假设您的 _buildName() 是您的小部件的一个方法,并且您从某个地方的 build 方法中调用它。

这意味着您可以将上下文或用户传递给此方法: _buildName(BuildContext context) _buildName(User user)

下次尝试提供更多代码,特别是调用方法的部分。

更新后编辑:

您需要在 buildName 方法中包含用户对象,因此您不能简单地执行 UserData.fullname,因为 UserData 是一个类而不是一个实例。

因此,要在 buildName 中获取数据,您需要将其更改为:

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

电话是这样的:_buildName(userData)

【讨论】:

这很有意义,看看我的代码,你是对的,我在小部件中调用它。但是我怎么能使用这个我展示的东西。我的意思是我的方法_builName 中的初始值。当我使用 userData.fullname 时,它​​显示未定义的名称 请只包含整个小部件,这样不可读 非常感谢:) 嘿抱歉,我有一个错误,我认为创建一个新问题没有用,我更新我的也许你可以检查一下。谢谢! 错误解释了您做错了什么,如果您无法弄清楚,请打开一个新问题

以上是关于如何在没有上下文的情况下使用提供者?的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有上下文的情况下导航?

在 *ngFor 的情况下,是啥为 ngTemplate 提供了上下文?

如何在没有上下文路径的情况下获取请求 URI?

如何修复“表达式类型'@lvalue CGRect/CGSize'在没有更多上下文的情况下模棱两可”?

使用Hook更新上下文状态值

在不嵌套提供者的情况下反应上下文?