从一个屏幕跳到另一个屏幕时,如何不丢失列表中的数据?

如何解决从一个屏幕跳到另一个屏幕时,如何不丢失列表中的数据?

我有一个ViewTotalItemProvider类,它扩展了ChangeNotifier。在课程内部,有一个像这样的列表。

class ViewTotalItemProvider extends ChangeNotifier{
List<CartPlantLists> cartPlantList3 = [];
}

此外,还有3个屏幕,包括PlantFeatureScreen1ParticularPlant2CartDetais3之类的类。所有这些都是有状态的小部件,我将在第二个屏幕中添加一些项目,即ParticularPlant2类。

当我尝试在第二个屏幕和第三个屏幕中显示列表中的项目时,它起作用了。
但是,该值不会在firstScreen(即PlantFeatureScreen1)中更新。但是,当我重新加载应用程序时,它会显示更新后的值。
为什么会这样呢?我该怎么解决?

代码
ViewTotalItemProvider

List<CartPlantLists> cartPlantList3 = [];

class ViewTotalItemProvider extends ChangeNotifier{

  addQuantity(index){
     cartPlantList3[index].qu++;
    notifyListeners();
  }

  subtrachQuantity(index){
    cartPlantList3[index].qu--;
    notifyListeners();

  }
}

firstScreen PlantFeatureScreen1(在这里我要更新最后一个小部件中的值)

class PlantFeatureScreen1 extends StatefulWidget {
  @override
  _PlantFeatureScreen1State createState() => _PlantFeatureScreen1State();
}

class _PlantFeatureScreen1State extends State<PlantFeatureScreen1> {


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ViewTotalItemProvider>(
      create: (context) => ViewTotalItemProvider(),child:Builder(builder: (context) {
        return           Column(
        children: <Widget>[
          TopAppBar(),Expanded(
            flex: 1,child: Align(
              alignment: Alignment(-1,0),child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,),child: Text(
                  "Plants",style: TextStyle(fontSize: 30,fontWeight: FontWeight.w700),Expanded(
            flex: 5,child: Container(
              width: double.infinity,decoration: BoxDecoration(
                color: Colors.blue,child: DefaultTabController(
                length: 5,child: Column(
                  children: [
                    Container(
                      height: 50,width: double.infinity,child: TabBar(
                        isScrollable: true,tabs: ourAllLists.tabMaker(),Container(
                      height: 317,decoration: BoxDecoration(color: Colors.white),child: TabBarView(
                        children: ourAllLists.tabViewerMaker(context),],Padding(
            padding: const EdgeInsets.fromLTRB(20,20,20),child: Container(
              alignment: Alignment.bottomRight,height: 120,child: Stack(
                overflow: Overflow.visible,children: [
                  Container(
                    height: 70,width: 105,decoration: BoxDecoration(
                        color: Color(0xFF96CA2D),borderRadius: BorderRadiusDirectional.horizontal(
                            end: Radius.circular(32),start: Radius.circular(32))),child: Icon(FontAwesomeIcons.shoppingBag,color:Colors.white,size:30),Positioned(
                    // top: 0,bottom: 50,right: 0,child: Consumer<ViewTotalItemProvider>(
                      builder: (context,value,child){
                        return Container(
                        height: 35,width: 35,decoration: BoxDecoration(
                          color: Colors.white,borderRadius: BorderRadius.circular(50),border: Border.all(color: Color(0xFF96CA2D),width: 4)
                        ),child: Center(child: Text(ourAllLists.totalquantity().toString(),style:TextStyle(fontSize: 20,color: Color(0xFF96CA2D)))),);
                      }),)
        ],);   
      })
 );
  }
}

secondScreen ParticularPlant2

class ParticularPlant2 extends StatefulWidget {
  final indexNumber;
  ParticularPlant2({@required this.indexNumber});

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

class _ParticularPlant2State extends State<ParticularPlant2> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.start,children: [
              TopAppBar(),Container(
                decoration: BoxDecoration(
                  color: Colors.red,borderRadius: BorderRadiusDirectional.only(
                    bottomStart: Radius.circular(50),child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,children: [
                    Text(
                      ourAllLists
                          .mainListAllPlantDetailsList1[widget.indexNumber].pN,style: kPlantNameStyle,Text(
                      ourAllLists
                          .mainListAllPlantDetailsList1[widget.indexNumber].ca
                          .toUpperCase(),style: TextStyle(
                        fontSize: 15,Text(
                      "\$" +
                          ourAllLists
                              .mainListAllPlantDetailsList1[widget.indexNumber]
                              .pr
                              .toString(),style: kItemPrice,SizedBox(height: 100),Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: [
                            Container(
                              height: 80,width: 80,decoration: BoxDecoration(
                                  color: Colors.white,borderRadius: BorderRadius.circular(50)),child: Icon(
                                FontAwesomeIcons.flag,color: Color(0xFF9DCD3C),SizedBox(
                              height: 50,FlatButton(
                              onPressed: () {
                                final tile = cartPlantList3.firstWhere(
                                    (item) =>
                                        item.pN ==
                                        ourAllLists
                                            .mainListAllPlantDetailsList1[
                                                widget.indexNumber]
                                            .pN,orElse: () => null);
                                if (tile != null) {
                                } else {
                                  cartPlantList3.add(
                                    CartPlantLists(
                                      quantity: 1,plantName: ourAllLists
                                          .mainListAllPlantDetailsList1[
                                              widget.indexNumber]
                                          .pN,category: ourAllLists
                                          .mainListAllPlantDetailsList1[
                                              widget.indexNumber]
                                          .ca,price: ourAllLists
                                          .mainListAllPlantDetailsList1[
                                              widget.indexNumber]
                                          .pr,);
                                }
                                print(cartPlantList3.length);
                              },child: Container(
                                height: 80,decoration: BoxDecoration(
                                    color: Color(0xFF9DCD3C),color: Colors.white),)
                          ],Container(
                          height: 250,child: Image(image: AssetImage("assets/tulip.png")),)
                      ],)
                  ],)
            ],);
  }
}

解决方法

似乎您使用提供者的方式错误。在您的方案中,执行此操作的最佳方法是使用MultiProvider将MaterialApp包裹在main.dart文件中的MyApp()中。尝试如下操作:https://pub.dev/packages/provider#multiprovider您可以在其中放置一个ChangeNotifierProvider。

return MultiProvider(
  providers: [
    ChangeNotifierProvider<ViewTotalItemProvider>(
        create: (context) => ViewTotalItemProvider()),],child: MaterialApp(...)
);

此外,您还必须在模型中放置吸气剂和吸气剂。这是一个示例:

class ImageModel extends ChangeNotifier {
  String _base64Image;
  get base64Image => _base64Image;
  set base64Image(String base64Image) {
    _base64Image = base64Image;
    notifyListeners();
  }
}

我还建议您使用Selector代替Consumer(理想情况下,您应该使用Selector代替Consumer,这样才使小部件仅在其侦听的值发生更改时才重建)这是基于上述模型的示例:

@override
Widget build(BuildContext context) {
 //other widgets
 Selector<ImageModel,String>(
  selector: (_,model) => model.base64Image,builder: (_,image,__) {
   return Text(image);
     },);
  }
 )
}

以下是使用RaisedButton进行设置的方法:

class _PlantFeatureScreen1State extends State<PlantFeatureScreen1> {
  final itemModel;
  List<CartPlantLists> myList=[];
  @override
  Widget build(BuildContext context) {
    itemModel = Provider.of<ViewTotalItemProvider>(context,listen:false);
    print(itemModel.yourVariable); //getting the value
    return Container(
             child: RaisedButton(
               child:Text("Set Item");
               onPressed:(){
               itemModel.yourVariable=myList; //setting the value
               },),);
  }
 }

希望这会有所帮助!祝你好运!

,

步骤1: 在 pubspec.yaml 文件

中添加提供者模式的依赖项
dependencies:
  flutter:
    sdk: flutter
  provider: ^4.1.2

步骤2: 在单独的文件中创建提供程序:

class ViewTotalItemProvider with ChangeNotifier{
List<CartPlantLists> _cartPlantList1 = [];
get cartPlantList1 => _cartPlantList1 ;

  set cartPlantList1 (List<CartPlantLists> selected){
   _cartPlantList1 = selected;
     notifyListeners();
  }
}

步骤3: 使用MultiProvider将MaterialApp小部件包装在 main.dart 中。


void main() => runApp(
   MultiProvider (providers: [
      ChangeNotifierProvider<ViewTotalItemProvider>.value(value: 
          ViewTotalItemProvider()),child: MyApp()
                )
            );
class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
        home: HomePage(),);
  }
}

第4步: 在屏幕PlantFeatureScreen1中使用提供程序:

class PlantFeatureScreen1 extends StatefulWidget {
  @override
  _PlantFeatureScreen1State createState() => _PlantFeatureScreen1State();
}

class _PlantFeatureScreen1State extends State<PlantFeatureScreen1> {
  var viewTotalItemProvider;
  @override
  Widget build(BuildContext context) {
    viewTotalItemProvider = Provider.of<ViewTotalItemProvider>(context);
    return Scaffold(
      .......
    );
  }
  }

步骤5: 获取cartPlantList1。

     List<CartPlantLists> list = viewTotalItemProvider.cartPlantList1; 

第6步:设置cartPlantList1。

    List<CartPlantLists> list = [];
    ...
    viewTotalItemProvider.cartPlantList1 = list;

类似地,您可以将其用于其他两个类。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-