【问题标题】:CurvedNavigationBar setState Error: Getter not found: 'userId'. Search(userId: userId,),CurvedNavigationBar setState 错误:找不到 Getter:'userId'。搜索(userId: userId,),
【发布时间】:2020-07-06 18:14:22
【问题描述】:

您好,我正在使用 Curved Navigation Bar 构建页面,它可能需要 StatefulWidget for setState();显示所需的页面。

我下面的代码在我无法使用 setState(); 的 StatelessWidget 中工作正常;表示我的 BottomNavBar 可见但无法导航。 如果我切换到 StatefullWidget,那么它会给我“错误:找不到 Getter:'userId'。搜索(userId:userId,)”。斜体下方也出现红色下划线。

搜索(userId: userId,),

class BottomNavBar extends StatefulWidget {
  final String userId;

  const BottomNavBar({this.userId});

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

}

class _BottomNavBarState extends State<BottomNavBar> {

  int _page = 2;
  final pages = [Settings(),
    Favorite(),
    Search(userId: userId,),
    Chats(),
    Account()
    ,];


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: CurvedNavigationBar(
          index: 2,
          height: 70.0,
          color: Colors.pinkAccent,
          buttonBackgroundColor: Colors.pink,
          animationDuration: Duration(milliseconds: 500),
          backgroundColor: Colors.white,
          animationCurve: Curves.easeInOut,
          onTap:(index){
            setState(() {
              _page = index;
            });
          },
          items: <Widget>[
            Icon(Icons.settings, color: Colors.white, size: 30),
            Icon(Icons.favorite_border,color: Colors.white, size: 30),
            Icon(Icons.home,color: Colors.white, size: 30),
            Icon(Icons.chat_bubble_outline,color: Colors.white, size: 30),
            Icon(Icons.perm_identity,color: Colors.white, size: 30),
          ]),
      body: pages [_page],
    );
  }
}

这是 Search() 类的代码

class Search extends StatefulWidget {
  final String userId;

  const Search({this.userId});

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

class _SearchState extends State<Search> {
  final SearchReposit _searchReposit = SearchReposit();
  SearchBloc _searchBloc;
  User _user, _currentUser;
  int difference;

  getDifference(GeoPoint userLocation) async {
    Position position = await Geolocator().getCurrentPosition();

    double location = await Geolocator().distanceBetween(userLocation.latitude,
        userLocation.longitude, position.latitude, position.longitude);

    difference = location.toInt();
  }

  @override
  void initState() {
    _searchBloc = SearchBloc(searchReposit: _searchReposit);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return BlocBuilder<SearchBloc, SearchState>(
      bloc: _searchBloc,
      builder: (context, state) {
        if (state is InitialSearchState) {
          _searchBloc.add(
            LoadUserEvent(userId: widget.userId),
          );
          return Center(
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation(Colors.blueGrey),
            ),
          );
        }
        if (state is LoadingState) {
          return Center(
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation(Colors.blueGrey),
            ),
          );
        }
        if (state is LoadUserState) {
          _user = state.user;
          _currentUser = state.currentUser;

          getDifference(_user.location);
          if (_user.location == null) {
            return Text(
              "No One Here",
              style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.black),
            );
          } else
            return profileWidget(
              padding: size.height * 0.035,
              photoHeight: size.height * 0.70,
              photoWidth: size.width * 0.80,
              photo: _user.photo,
              clipRadius: size.height * 0.02,
              containerHeight: size.height * 0.3,
              containerWidth: size.width * 0.9,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: size.width * 0.02),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: size.height * 0.06,
                    ),
                    Row(
                      children: <Widget>[
                        userGender(_user.gender),
                        Expanded(
                          child: Text(
                            " " +
                                _user.name +
                                ", " +
                                (DateTime.now().year - _user.age.toDate().year)
                                    .toString(),
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: size.height * 0.05),
                          ),
                        )
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Icon(
                          Icons.location_on,
                          color: Colors.white,
                        ),
                        Text(
                          difference != null
                              ? (difference / 1000).floor().toString() +
                              "km away"
                              : "away",
                          style: TextStyle(color: Colors.white),
                        )
                      ],
                    ),
                    SizedBox(
                      height: size.height * 0.05,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: <Widget>[
                        iconWidget(EvaIcons.flash, () {}, size.height * 0.04,
                            Colors.yellow),
                        iconWidget(Icons.clear, () {
                          _searchBloc
                              .add(PassUserEvent(widget.userId, _user.uid));
                        }, size.height * 0.08, Colors.blue),
                        iconWidget(FontAwesomeIcons.solidHeart, () {
                          _searchBloc.add(
                            SelectUserEvent(
                                name: _currentUser.name,
                                photoUrl: _currentUser.photo,
                                currentUserId: widget.userId,
                                selectedUserId: _user.uid),
                          );
                        }, size.height * 0.06, Colors.red),
                        iconWidget(EvaIcons.options2, () {}, size.height * 0.04,
                            Colors.white)
                      ],
                    )
                  ],
                ),
              ),
            );
        } else
          return Container();
      },
    );
  }
}

这个带有 Statelesswidget 的代码可以正常工作,但我无法从 BottomNavBar 更改页面,因为不包含 setState。

class BottomNavBar extends StatelessWidget {

  final userId;

  const BottomNavBar({this.userId});
    @override
    Widget build(BuildContext context) {
      int _page = 2;
      final pages = [
        Settings(),
        Favorite(),
        Search( userId:  userId,
        ),
        Chats(),
        Account()
        ,
      ];
      return Scaffold(
        bottomNavigationBar: CurvedNavigationBar(
            index: 2,
            height: 70.0,
            color: Colors.pinkAccent,
            buttonBackgroundColor: Colors.pink,
            animationDuration: Duration(milliseconds: 500),
            backgroundColor: Colors.white,
            animationCurve: Curves.easeInOut,
          //onTap:(index){
//            setState(() {
//              _page = index;
//            });
         // },
            onTap: (index) {
//            setState(() {
//              _page = index;
//            });
            },
            items: <Widget>[

              Icon(Icons.settings, color: Colors.white, size: 30,),
              Icon(Icons.favorite_border, color: Colors.white, size: 30),
              Icon(Icons.home, color: Colors.white, size: 30),
              Icon(Icons.chat_bubble_outline, color: Colors.white, size: 30),
              Icon(Icons.perm_identity, color: Colors.white, size: 30),
            ]),
        body: pages [_page],
      );
    }
  }

【问题讨论】:

    标签: android flutter dart search location


    【解决方案1】:

    变量userId 不存在于类_BottomNavBarState,它是BottomNavBar 的一部分。为了从状态访问它,你需要做widget.userId

    另外,将pages的初始化移动到initState

    @override
    void initState() {
        super.initState();
    
        pages = [Settings(),
           Favorite(),
           Search(userId: userId,),
           Chats(),
           Account()];
    }
    

    【讨论】:

    • 感谢克劳迪奥的快速回复,
    • 我也尝试过,但在这种情况下,widget.userId“widget”带有错误下划线(只有静态成员可以访问初始化程序)我已经更新了上面的问题并提到了返回类的 Search() 代码.如果我将第一个代码更改为无状态小部件并删除 setState 函数,它工作正常,但导航栏由于 setState 函数而没有显示其他页面。
    • 更新了我的答案@David。您需要将 pages 初始化移动到其他地方。
    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2019-10-08
    • 1970-01-01
    相关资源
    最近更新 更多