为啥即使在有状态小部件中使用 setstate 也无法获取更新的变量。因为我想在新的 TabBar 选项上更新我的 Container

Posted

技术标签:

【中文标题】为啥即使在有状态小部件中使用 setstate 也无法获取更新的变量。因为我想在新的 TabBar 选项上更新我的 Container【英文标题】:Why I'm not able to get the updated variable even using setstate inside the stateful widget. As I want to update my Container on new TabBar option为什么即使在有状态小部件中使用 setstate 也无法获取更新的变量。因为我想在新的 TabBar 选项上更新我的 Container 【发布时间】:2022-01-01 21:50:56 【问题描述】:

基本上我想在选择 TabBar 选项时更改内容。这是我的代码。我也是颤振的新手。我还创建了一个 _incrementCounter() 和 getter setter 方法。通过使用 _incrementCounter() 我返回一个整数,以更新我的屏幕的 PAgeView,它在一个名为 tabsCat 的列表中实现。但是在第 264 行调用 _incrementCounter() 方法时,它没有给出更新的值,请指导。

import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:fluttertravelapp/models/beach_model.dart';
import 'package:fluttertravelapp/models/new_category_model.dart';
import 'package:fluttertravelapp/models/popular_model.dart';
import 'package:fluttertravelapp/models/recommended_model.dart';
import 'package:fluttertravelapp/screens/selected_category_screen.dart';
import 'package:fluttertravelapp/screens/selected_place_screen.dart';
import 'package:fluttertravelapp/widgets/bottom_navigation_bar.dart';
import 'package:fluttertravelapp/widgets/custom_tab_indicator.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';


class HomeScreen extends StatefulWidget 
  @override
  _HomeScreenState createState() => _HomeScreenState();


class _HomeScreenState extends State<HomeScreen> 
  int count = 0;

  // Creating the getter method
  // to get input from Field/Property
  int get getCount 
    return count;
  

  // Creating the setter method
  // to set the input in Field/Property
  set setCount(int newCount) 
    count = newCount;
  

  int _incrementCounter() 
    int index = 0;
    setState(() 
      index = getCount;
      print(index);
    );
    return index;
  

  /// Page Controller
  final _pageController = PageController(viewportFraction: 0.877);

  @override
  Widget build(BuildContext context) 
    int tabIndex = 0;
    List tabsCat = [
      PageView(
        physics: BouncingScrollPhysics(),
        controller: _pageController,
        scrollDirection: Axis.horizontal,
        children: List.generate(
          recommendations.length,
              (int index) => GestureDetector(
            onTap: () 
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => SelectedCategoryScreen(
                      newCategoryModel: newCategories[index])));
            ,
            child: Container(
              margin: EdgeInsets.only(right: 28.8),
              width: 333.6,
              height: 218.4,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(9.6),
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: AssetImage(newCategories[index].image),
                ),
              ),
              child: Stack(
                children: <Widget>[
                  Positioned(
                    bottom: 19.2,
                    left: 19.2,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4.8),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(
                            sigmaY: 19.2, sigmaX: 19.2),
                        child: Container(
                          height: 36,
                          padding: EdgeInsets.only(
                              left: 16.72, right: 14.4),
                          alignment: Alignment.centerLeft,
                          child: Row(
                            children: <Widget>[
                              SvgPicture.asset(
                                  'assets/svg/icon_location.svg'),
                              SizedBox(
                                width: 9.52,
                              ),
                              Text(
                                recommendations[index].name,
                                style: GoogleFonts.lato(
                                    fontWeight: FontWeight.w700,
                                    color: Colors.white,
                                    fontSize: 16.8),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
      PageView(
        physics: BouncingScrollPhysics(),
        controller: _pageController,
        scrollDirection: Axis.horizontal,
        children: List.generate(
          recommendations.length,
              (int index) => GestureDetector(
            onTap: () 
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => SelectedCategoryScreen(
                      newCategoryModel: newCategories[index])));
            ,
            child: Container(
              margin: EdgeInsets.only(right: 28.8),
              width: 333.6,
              height: 218.4,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(9.6),
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: CachedNetworkImageProvider(recommendations[index].image),
                ),
              ),
              child: Stack(
                children: <Widget>[
                  Positioned(
                    bottom: 19.2,
                    left: 19.2,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4.8),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(
                            sigmaY: 19.2, sigmaX: 19.2),
                        child: Container(
                          height: 36,
                          padding: EdgeInsets.only(
                              left: 16.72, right: 14.4),
                          alignment: Alignment.centerLeft,
                          child: Row(
                            children: <Widget>[
                              SvgPicture.asset(
                                  'assets/svg/icon_location.svg'),
                              SizedBox(
                                width: 9.52,
                              ),
                              Text(
                                recommendations[index].name,
                                style: GoogleFonts.lato(
                                    fontWeight: FontWeight.w700,
                                    color: Colors.white,
                                    fontSize: 16.8),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    ];
    return Scaffold(
      //bottomNavigationBar: BottomNavigationBarTravel(),
      body: SafeArea(
        child: Container(
          child: ListView(
            physics: BouncingScrollPhysics(),
            children: <Widget>[
              /// Custom Navigation Drawer and Search Button
              Container(
                height: 57.6,
                margin: EdgeInsets.only(top: 28.8, left: 28.8, right: 28.8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[

                  ],
                ),
              ),

              /// Text Widget for Title
              Padding(
                padding: EdgeInsets.only(top: 0, left: 28.8),
                child: Text(
                  'Explore\nPakistan',
                  style: GoogleFonts.playfairDisplay(
                      fontSize: 45.6, fontWeight: FontWeight.w700),
                ),
              ),

              /// Custom Tab bar with Custom Indicator
              Column(
                children:
                [DefaultTabController(
                  length: 4,
                  child: TabBar(
                      labelPadding: EdgeInsets.only(left: 14.4, right: 14.4),
                      indicatorPadding:
                      EdgeInsets.only(left: 14.4, right: 14.4),
                      isScrollable: true,
                      labelColor: Color(0xFF000000),
                      unselectedLabelColor: Color(0xFF8a8a8a),
                      labelStyle: GoogleFonts.lato(
                          fontSize: 14, fontWeight: FontWeight.w700),
                      unselectedLabelStyle: GoogleFonts.lato(
                          fontSize: 14, fontWeight: FontWeight.w700),
                      indicator: RoundedRectangleTabIndicator(
                          color: Color(0xFF000000), weight: 2.4, width: 14.4),
                      onTap: (index)
                        setCount = index;
                        //print(getCount);
                      ,

                      tabs: [
                        Tab(
                          child: Container(
                            child: Text('Recommended'),
                          ),
                        ),
                        Tab(
                          child: Container(
                            child: Text('Popular'),
                          ),
                        ),
                        Tab(
                          child: Container(
                            child: Text('New Destination'),
                          ),
                        ),
                        Tab(
                          child: Container(
                            child: Text('Hidden Gems'),
                          ),
                        )
                      ]),
                ),


              /// ListView widget with PageView
              /// Recommendations Section
              Container(
                height: 218.4,
                margin: EdgeInsets.only(top: 16),
                child: tabsCat[_incrementCounter()],
              ),
                ]),
              /// Dots Indicator
              /// Using SmoothPageIndicator Library
              Padding(
                padding: EdgeInsets.only(left: 28.8, top: 28.8),
                child: SmoothPageIndicator(
                  controller: _pageController,
                  count: recommendations.length,
                  effect: ExpandingDotsEffect(
                      activeDotColor: Color(0xFF8a8a8a),
                      dotColor: Color(0xFFababab),
                      dotHeight: 4.8,
                      dotWidth: 6,
                      spacing: 4.8),
                ),
              ),

              /// Text Widget for Popular Categories
              Padding(
                padding: EdgeInsets.only(top: 48, left: 28.8, right: 28.8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.width*0.4,
                      child: FittedBox(
                        child: Text(
                          'Popular Categories',
                          style: GoogleFonts.playfairDisplay(
                            fontWeight: FontWeight.w700,
                            color: Color(0xFF000000),
                          ),
                        ),
                      ),
                    ),
                    Container(width: MediaQuery.of(context).size.width*0.1,
                      child: FittedBox(
                        child: Text(
                          'Show All ',
                          style: GoogleFonts.lato(
                            fontWeight: FontWeight.w500,
                            color: Color(0xFF8a8a8a),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),

              /// ListView for Popular Categories Section
              Container(
                margin: EdgeInsets.only(top: 33.6),
                height: 45.6,
                child: ListView.builder(
                  itemCount: populars.length,
                  scrollDirection: Axis.horizontal,
                  physics: BouncingScrollPhysics(),
                  padding: EdgeInsets.only(left: 28.8, right: 9.6),
                  itemBuilder: (context, index) 
                    return Container(
                      margin: EdgeInsets.only(right: 19.2),
                      height: 45.6,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(9.6),
                        color: Color(populars[index].color),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          SizedBox(
                            width: 19.2,
                          ),
                          Image.asset(
                            populars[index].image,
                            height: 16.8,
                          ),
                          SizedBox(
                            width: 19.2,
                          )
                        ],
                      ),
                    );
                  ,
                ),
              ),

              /// ListView for Beach Section
              Container(
                margin: EdgeInsets.only(top: 28.8, bottom: 16.8),
                height: 124.8,
                child: ListView.builder(
                  itemCount: beaches.length,
                  padding: EdgeInsets.only(left: 28.8, right: 12),
                  scrollDirection: Axis.horizontal,
                  physics: BouncingScrollPhysics(),
                  itemBuilder: (context, index) 
                    return Container(
                      height: 124.8,
                      width: 188.4,
                      margin: EdgeInsets.only(right: 16.8),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(9.6),
                        image: DecorationImage(
                          fit: BoxFit.cover,
                          image:
                          CachedNetworkImageProvider(beaches[index].image),
                        ),
                      ),
                    );
                  ,
                ),
              )
            ],
          ),
        ),
      ),
    );
  

通过在 OnTap 部分调用 _incrementcounter 方法来解决错误。这是我的代码更改:

编辑 incrementcounter 方法并声明新方法 setNewCount,

  void setNewCount(int newCount) 
    count = newCount;
  

  void _incrementCounter() 
    setState(() 
      count = getCount;
    );
  

第二次改变:

 onTap: (index)
  setNewCount(index);
  _incrementCounter();
,

第三次变化:

Container(
   height: 218.4,
   margin: EdgeInsets.only(top: 16),
   child: tabsCat[count],
   ),

【问题讨论】:

【参考方案1】:

试试

onTap: (index)
    setCount(index);
    //print(getCount);
,

而不是

onTap: (index)
    setCount = index;
    //print(getCount);
,

【讨论】:

它给出了一个错误。 想要添加,我的代码没有给出任何错误,但我想要从增量计数器更新索引。你所说的也不是为 Setter 方法设置值的方法。 我的朋友有什么更新吗? 删除 setCount 方法之前的集合。 ``` setCount(int newCount) count = newCount; ``` 感谢 Hüseyin Gözübenli 能够解决问题。谢谢兄弟。

以上是关于为啥即使在有状态小部件中使用 setstate 也无法获取更新的变量。因为我想在新的 TabBar 选项上更新我的 Container的主要内容,如果未能解决你的问题,请参考以下文章

我的有状态小部件不会更新 ui,即使我正在调用 setState 并将正确的值传递给小部件类

为啥小部件的状态在颤动时没有改变?

在 Flutter 中使用 BLoC - 在有状态小部件与无状态小部件中的使用

为啥我无法访问小部件中的变量?

在颤振中从父小部件调用 setState 不会更新状态

调用 setState 时,我的有状态小部件不会更新其状态