flutter listview skroll 重置文本小部件中的计数器

问题描述

我让这个测试应用程序部分工作。它会更新百吉饼计数器,但会更新屏幕上的所有百吉饼计数器。我将 cubit build.provider 移至仅显示屏幕上每个项目计数的文本字段。

这修复了我对所有百吉饼数量的全局更新。所以每个人现在都维护自己的计数器。但是现在当我滚出屏幕时,计数都被重置了。我将 + 0 1 计数器作为一个类拉入列表视图中。

我曾尝试添加密钥和 addAutomaticKeepAlives:正确但没有运气。修复删除 + 之间计数器 0 的滚动 - 正在重置..

main.dart

    //Todo Screen Layouts
//Todo json pull and post
//Todo where to send post to email sms for store to see
//Todo Update live db with fields add to test dp  retailp and mobileactive
//Todo Create batch process to generate json file from db nightly or on demain via a button
//Todo TEST code
//Todo spining on load bagel icon or sprit - make.
//Todo total bagels / breads order
//Todo shopping card added
//Todo snackbar menu for as total add up pop up totals

import 'package:Flutter/material.dart';
import 'Services.dart';
import 'Product.dart';
import 'bagelcounter.dart';
import 'cubit/counter_state.dart';
import 'cubit/counter_cubit.dart';
import 'cubit/counter_cubit_page.dart';
import 'package:Flutter_bloc/Flutter_bloc.dart'; //addded

void main() => runApp(MyApp());

// #docregion MyApp
class MyApp extends StatelessWidget {
  final bool keepAlive = true;    // not working 
  // #docregion build
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Startup Name Generator',theme: ThemeData(
        // Add the 3 lines from here...
        primarySwatch: Colors.blue,textTheme: TextTheme(
          headline1: TextStyle(
            fontFamily: 'Corben',fontWeight: FontWeight.w700,fontSize: 24,color: Colors.black,),// ... to here.
      home: buildJsonParseDemo(),// org      home: buildJsonParseDemo(),);
  }

  JsonParseDemo buildJsonParseDemo() => JsonParseDemo();
  // #enddocregion build
}

class JsonParseDemo extends StatefulWidget {
  //
  JsonParseDemo() : super();

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

class _JsonParseDemoState extends State<JsonParseDemo> {
  //
  List<Product> _product;
  bool _loading;

//quick fix make this getter
//static //todo make live counter
  int mbakerdoz = 0;
  //get bakerdoz => mbakerdoz;

//static  //todo make live counter
  int singles = 10;

  @override
  void initState() {
    super.initState();
    _loading = true;
    Services.getUsers().then((product) {
      setState(() {
        _product = product;
        _loading = false;
      });
    });
  }
  //Todo find day of week to only see items available on day:
  //DateTime date = DateTime.Now();
  //print("weekday is ${date.weekday}");
//Todo Add quantiy field of 1 - 6,default 0,to bagel and breads

//Todo Bottom total of item and price.  Tax not included

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(
        title: Text(_loading ? 'Loading...' : 'Bagels & Breads'),body: Container(
        color: Colors.white,child: ListView.separated(
          key: UniqueKey(),addAutomaticKeepAlives: true,//not working to sotp skroll delete
          // key: UniqueKey(),key not fix update all.
          separatorBuilder: (context,index) => Divider(
            color: Colors.black,thickness: 2,itemCount: null == _product ? 0 : _product.length,itemBuilder: (context,index) {
            Product product = _product[index];
            return ListTile(
              key: UniqueKey(),isThreeLine: true,// leading: Icon(Icons.plus_one),// trailing: Icon(Icons.exposure_minus_1),title: Text(product.pname,style: TextStyle(
                      color: Colors.blue[900],fontSize: 22.0,fontWeight: FontWeight.w500)),// product name

              subtitle: Text(
                   
                  '\$ ' +
                      (product.retailp.toStringAsFixed(2) +
                          '  each   index:' +
                          '$index  ' +
                          ' qty ' +
                          product.qty.toString()),key: UniqueKey(),style: TextStyle( 
                      color: Colors.black,fontSize: 18.0,fontWeight: FontWeight.w400)
                      ),trailing: SizedBox(
                key: UniqueKey(),width: 150,child: BlocProvider<CounterCubit>(
                    key: UniqueKey(),create: (context) => CounterCubit(),child: CounterCubitPage(),)),);
          },bottomNavigationBar: BottomAppBar(
        child: Row(
          children: [
            //IconButton(icon: Icon(Icons.menu),onpressed: () {}),Spacer(),Container(
              height: 55.0,width: 1.0,//Todo get bakerdoz and etotal on footer working need to pass data between main and bagelcounter

            Text("Baker's Dozen: $mbakerdoz " + "    Singles:  $singles",style: TextStyle(
                    color: Colors.white,fontSize: 20.0,//IconButton(icon: Icon(Icons.search),//IconButton(icon: Icon(Icons.more_vert),],shape: CircularNotchedRectangle(),color: Colors.lightBlue,notchMargin: 8.0,//floatingActionButton:
      //    FloatingActionButton(child: Icon(Icons.add),//floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,);
  }
}


counter_cubit_page.dart

    import 'package:Flutter/material.dart';
import 'package:Flutter_bloc/Flutter_bloc.dart';
import 'counter_cubit.dart';
import 'counter_state.dart';

class CounterCubitPage extends StatelessWidget {
  // static const String routeName = '/counter_cubit';
  
  //@override
  //  bool get wantKeepAlive => true;  // not work
 // final bool keepAlive = true; // try to keep counter on skroll????

  @override
  Widget build(BuildContext context) => Scaffold(
    key: UniqueKey(),//appBar: AppBar(title: const Text('Counter Cubit Bloc Double CTest')),body: BlocBuilder<CounterCubit,CounterCubitState>(
          key: UniqueKey(),builder: (context,state) => Column(
            children: [
              Row(
                key: UniqueKey(),mainAxisAlignment: MainAxisAlignment.center,children: [
                  IconButton(
                    icon: Icon(Icons.add_circle),color: Colors.blue,iconSize: 25,onpressed: () => context.read<CounterCubit>().increment(),Text(
                    '${state.totalbagels}',key: GlobalKey(),// not working 
                    style: Theme.of(context).textTheme.headline4,IconButton(
                    icon: Icon(Icons.remove_circle),onpressed: () => context.read<CounterCubit>().decrement(),);
}

我曾尝试 addAutomaticKeepAlives: true 不起作用并尝试在字段上使用唯一键...

欢迎任何指点。我是 Flutter 编码的新手.. 还有很多东西要学..

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)