状态管理器正在不断地重建小部件而不是更新,如何消除这种情况?扑

如何解决状态管理器正在不断地重建小部件而不是更新,如何消除这种情况?扑

所以我在整理如何将数据动态添加到我的 DataGrid 时遇到了麻烦。我从 Syncfusion 支持人员那里得到了帮助,他们到目前为止都非常出色。但是我仍然无法获得完整和正确的功能。

我正在使用 GetX GetBuilder 来包装 DataGrid。它从数据库接收数据,并在添加数据库时更新此数据。然而,它目前正在连续运行,或者说每秒 50 倍。这在很多方面显然都不好。但是我目前有完整的功能,但它不合适。

我在 GridSource 构造函数中加入了一个打印语句,它会连续打印。所以出了点问题,我想不通。我曾尝试移动构建器(从构建器中移出)以及 dataSource 声明,但是这完全破坏了网格加载的功能。

这里是完整的演示项目 here

有人可以指出我做错了什么吗?

DataGrid 屏幕:

import 'package:flutter/material.dart';
import 'package:getx_hive_demo_one/presentation/event_list_screen/add_event_button.dart';
import 'package:get/get.dart';
import 'package:getx_hive_demo_one/database/database.dart';
import 'package:getx_hive_demo_one/models/event.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class EventListScreen extends StatelessWidget {
  final Database database = Get.put(Database());

  GridSource dataSource;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Event Dashboard'),backgroundColor: Colors.grey[850],actions: [AddEventButton(source: dataSource)],),body: SafeArea(child: GetBuilder<Database>(
          builder: (database) {
            dataSource = GridSource(database.getEventList());
            return SfDataGrid(
              source: dataSource,columnWidthMode: ColumnWidthMode.fill,columns: <GridColumn>[
                GridTextColumn(
                    columnName: 'name',label: Container(
                        color: Colors.grey[800],padding: EdgeInsets.all(8.0),alignment: Alignment.centerLeft,child: Text(
                          'Event',style: TextStyle(color: Colors.white),))),GridTextColumn(
                    columnName: 'start',child: Text(
                          'Start Date',GridTextColumn(
                    columnName: 'duration',child: Text(
                          'Event Duration',overflow: TextOverflow.ellipsis,GridTextColumn(
                    columnName: 'invitees',child: Text(
                          'Attendees',GridTextColumn(
                    columnName: 'location',child: Text(
                          'Location',],);
          },)));
  }
}

class GridSource extends DataGridSource {
  List<DataGridRow> _eventGridRow = [];
  List<Event> eventGrid = [];

  GridSource(this.eventGrid) {
    print('Run');
    buildDataGridRows();
  }

  void buildDataGridRows() {
    _eventGridRow = eventGrid
        .map<DataGridRow>(
          (event) => DataGridRow(
            cells: [
              DataGridCell<String>(columnName: 'name',value: event.eventName),DataGridCell<String>(columnName: 'start',value: event.eventStart.toString()),DataGridCell<String>(columnName: 'duration',value: event.eventDuration.toString()),DataGridCell<String>(columnName: 'invitees',value: event.numberInvitees.toString()),DataGridCell<String>(columnName: 'location',value: event.location),)
        .toList();
  }

  @override
  List<DataGridRow> get rows => _eventGridRow;

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    final int index = _eventGridRow.indexOf(row);
    Color getRowBackgroundColor() {
      if (index % 2 == 0) {
        return Colors.grey[100];
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
      color: getRowBackgroundColor(),cells: [
        Container(
          alignment: Alignment.centerLeft,child: Text(
            row.getCells()[0].value ?? '',Container(
          alignment: Alignment.centerLeft,child: Text(
            row.getCells()[1].value ?? '',child: Text(
            row.getCells()[2].value ?? '',child: Text(
            row.getCells()[3].value ?? ' ',child: Text(
            row.getCells()[4].value ?? '',);
  }

  void updateDataGridSource() {
    notifyListeners();
  }
}

连续打印语句:

flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run
flutter: Run

解决方法

问题是由于每次都创建 GridSource 以及在 buildDataRow 内部,您正在调用 getEventList 并刷新,因此它是循环的。请将 DataBase 和 DataGrid 替换为以下提供代码片段

数据库

import 'package:flutter/foundation.dart';

///
///
/// HIVE DATABASE MODEL USING ENCRYPTION AND CRUD ACTIONS

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:getx_hive_demo_one/models/event.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'dart:convert';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:flutter/material.dart';

class Database extends GetxController {
  GridSource dataGridSource;

  Database() {
    dataGridSource = GridSource(this);
  }

  // Hive box name
  String _boxName = 'database';

  // Initialize our list of contacts
  List<Event> eventList = [];

  // Holds our active contact
  Event _activeEvent;

  ///
  ///
  /// Encrypted Box
  /// Create & open encrypted box
  /// Return encrypted box for other methods to have box
  Future<Box<Event>> encryptedBox() async {
    final FlutterSecureStorage secureStorage = const FlutterSecureStorage();
    var containsEncryptionKey = await secureStorage.containsKey(key: 'key');
    if (!containsEncryptionKey) {
      var key = Hive.generateSecureKey();
      await secureStorage.write(key: 'key',value: base64UrlEncode(key));
    }
    var encryptionKey = base64Url.decode(await secureStorage.read(key: 'key'));
    var box = await Hive.openBox<Event>(_boxName,encryptionCipher: HiveAesCipher(encryptionKey));
    return box;
  }

  ///
  ///
  /// Create Event
  /// Saves data to hive box,updates repository & notify listeners
  void addEvent(Event newEvent) async {
    var box = await Hive.openBox<Event>(_boxName);
    await box.add(newEvent);
    eventList = box.values.toList();
    refresh();
  }

  ///
  ///
  /// Read Event
  /// Sends events in database to list repository
  void getEvents() async {
    var box = await Hive.openBox<Event>(_boxName);
    eventList = box.values.toList();
    refresh();
  }

  ///
  ///
  /// Read Event
  /// Returns event list
  List<Event> getEventList() {
    getEvents();
    return eventList;
  }

  ///
  ///
  /// Read Event
  /// Gets contact by index from repository
  Event getEvent(index) {
    return eventList[index];
  }

  ///
  ///
  /// Read Event
  /// Gets length of event repository
  int get eventCount {
    return eventList.length;
  }

  ///
  ///
  /// Read Event
  /// Sets active event to notify listeners for
  void setActiveEvent(key) async {
    var box = await Hive.openBox<Event>(_boxName);
    _activeEvent = box.get(key);
    refresh();
  }

  ///
  ///
  /// Read Event
  /// Get active event
  Event getActiveEvent() {
    return _activeEvent;
  }

  ///
  ///
  /// Update Event
  /// Updates event info with new data
  void editEvent({Event event,int eventKey}) async {
    var box = await Hive.openBox<Event>(_boxName);
    await box.put(eventKey,event);
    eventList = box.values.toList();
    _activeEvent = box.get(eventKey);
    refresh();
  }

  void deleteAll() async{
    var box = await Hive.openBox<Event>(_boxName);
    box.deleteFromDisk();
    refresh();
  }

  ///
  ///
  /// Delete Event
  /// Deletes event from box and updates list
  void deleteEvent(key) async {
    var box = await Hive.openBox<Event>(_boxName);
    await box.delete(key);
    eventList = box.values.toList();
    print('Deleted event at:' + key.toString());
    refresh();
  }

  /// Non-encrypted box
  /// var box = await Hive.openBox<Event>(_boxName);
}

class GridSource extends DataGridSource {


List<DataGridRow> _eventGridRow = [];
  final Database database;
  List eventList = [];

  GridSource(this.database) {
    this.database.addListener(handleListChanges);
  }

  void handleListChanges() {
    if (!listEquals(eventList,this.database.eventList)) {
      eventList = this.database.eventList;
      buildDataGridRows();
      notifyListeners();
    }
  }

  void buildDataGridRows() {
    _eventGridRow = eventList
        .map<DataGridRow>(
          (event) => DataGridRow(
            cells: [
              DataGridCell<String>(columnName: 'name',value: event.eventName),DataGridCell<String>(
                  columnName: 'start',value: event.eventStart.toString()),DataGridCell<String>(
                  columnName: 'duration',value: event.eventDuration.toString()),DataGridCell<String>(
                  columnName: 'invitees',value: event.numberInvitees.toString()),DataGridCell<String>(
                  columnName: 'location',value: event.location),],),)
        .toList();
  }

  @override
  List<DataGridRow> get rows => _eventGridRow;

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    final int index = _eventGridRow.indexOf(row);
    Color getRowBackgroundColor() {
      if (index % 2 == 0) {
        return Colors.grey[100];
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
      color: getRowBackgroundColor(),cells: [
        Container(
          alignment: Alignment.centerLeft,padding: EdgeInsets.all(8.0),child: Text(
            row.getCells()[0].value,overflow: TextOverflow.ellipsis,Container(
          alignment: Alignment.centerLeft,child: Text(
            row.getCells()[1].value,child: Text(
            row.getCells()[2].value,child: Text(
            row.getCells()[3].value,child: Text(
            row.getCells()[4].value,);
  }
}

数据网格页面

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_hive_demo_one/database/database.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class DataGrid extends StatelessWidget {
  final Database database = Get.put(Database());


  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          body: GetBuilder<Database>(
              builder: (database) {
                return SfDataGrid(
                  source: database.dataGridSource,columnWidthMode: ColumnWidthMode.fill,columns: <GridColumn>[
                    GridTextColumn(
                        columnName: 'name',label: Container(
                            color: Colors.grey[800],alignment: Alignment.centerLeft,child: Text(
                              'Event',style: TextStyle(color: Colors.white),))),GridTextColumn(
                        columnName: 'start',child: Text(
                              'Start Date',GridTextColumn(
                        columnName: 'duration',child: Text(
                              'Event Duration',GridTextColumn(
                        columnName: 'invitees',child: Text(
                              'Attendees',GridTextColumn(
                        columnName: 'location',child: Text(
                              'Location',);
              })),);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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-