You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter定时调用函数无法更新DataTable状态问题求助

问题解决:定时调用函数后DataTable不更新的原因及修复

核心问题

你代码里存在两个完全独立的MyAppState实例:

  • _HomePageState里手动new的appState,定时任务更新的是这个本地实例
  • build方法里通过context.watch<MyAppState>()获取的是全局Provider管理的实例

UI监听的是全局实例的状态变化,定时任务更新的却是本地实例,所以DataTable完全感知不到数据变化。

修复步骤

  1. 移除本地实例:删掉_HomePageState里的var appState = MyAppState();
  2. 统一用全局实例:在initState里通过context.read<MyAppState>()获取全局状态实例(initState阶段不能用watch)
  3. 封装状态更新方法:在MyAppState里写一个带notifyListeners()的方法,用来更新数据并主动通知UI
  4. 统一调用更新方法:定时任务和按钮点击都调用这个封装的方法,避免重复逻辑

修改后的完整代码示例

MyAppState部分

class MyAppState extends ChangeNotifier {
  List listaContoareTensiuni = [];
  // 保留你原有的其他变量和方法

  // 封装统一的更新方法
  Future<void> updateTensiuni() async {
    listaContoareTensiuni.clear();
    var data = await VoltageCheck(169);
    listaContoareTensiuni = data;
    notifyListeners(); // 强制通知UI刷新
  }
}

HomePage部分

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    // 获取全局状态实例
    final appState = context.read<MyAppState>();
    Timer.periodic(const Duration(seconds: 5), (Timer t) async {
      await appState.updateTensiuni();
    });
  }

  @override
  Widget build(BuildContext context) {
    final appState = context.watch<MyAppState>();

    return Scaffold(
      backgroundColor: const Color.fromRGBO(59, 255, 252, .8),
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () async {
                await appState.updateTensiuni();
              },
              child: const Text(
                "Refresh Tensiuni",
                style: TextStyle(
                    color: Color.fromRGBO(5, 5, 5, .8),
                    fontSize: 15,
                    fontWeight: FontWeight.bold),
              ),
            ),
            DataTable(
              horizontalMargin: 0,
              dataRowColor: MaterialStateProperty.resolveWith(
                  appState._getDataRowColor),
              dataRowHeight: 30,
              headingRowHeight: 50,
              border: TableBorder.all(
                  color: const Color.fromARGB(255, 4, 34, 32),
                  style: BorderStyle.solid,
                  borderRadius: BorderRadius.circular(10),
                  width: 2),
              columnSpacing: 0,
              columns: appState.getColumns_tensiuni(appState.columns_tensiuni),
              rows: appState.getRows_tensinui(appState.listaContoareTensiuni),
            ),
          ],
        ),
      ),
    );
  }
}

额外注意

确保你已经在App顶层通过ChangeNotifierProvider注册了MyAppState,比如在main.dart里:

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => MyAppState(),
      child: const MyApp(),
    ),
  );
}

内容的提问来源于stack exchange,提问作者Catalin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:53:14