首页 > 解决方案 > 在 Flutter 中从 main() 调用 setState()

问题描述

在我调用 main() 的每个 Cron-Job 之后,如何调用特定 State-Class 的 setState() 方法?

主要的():

void main() async {
    new Cron().schedule(new Schedule.parse('* * * * *'), () async {
        uploadDocuments();
    });

    runApp(MaterialApp(
        home: MainMenu(),
    ));
}

类,我希望在其中调用 setState():

class DbObjectsDetails extends StatefulWidget 

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

class _DbObjectsDetailsState extends State<DbObjectsDetails> {

    void initState() {
        loadFilesFromDatabase(true);
    }
}

标签: flutterdartsetstate

解决方案


您可以尝试使用get_it包注册一个单例,GlobalKey然后在两个地方都使用它

此代码可能有效:

import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';

GetIt locator = GetIt.instance..allowReassignment = true;

void setupLocator() {
  locator.registerLazySingleton(() => GlobalKey<DbObjectsDetailsState>());
}

GlobalKey<DbObjectsDetailsState> newWidgetKey() {
  locator.registerSingleton(GlobalKey<DbObjectsDetailsState>());
  return locator<GlobalKey<DbObjectsDetailsState>>();
}

void main() async {
  setupLocator()
  new Cron().schedule(new Schedule.parse('* * * * *'), () async {
    //you can acces the current state of the widget like that:
    locator<GlobalKey<DbObjectsDetailsState>>().currentState?.rebuild();});
    
      runApp(MaterialApp(
        home: DbObjectsDetails(key: newWidgetKey()),
      ));
    }
    
    class DbObjectsDetails extends StatefulWidget {
      DbObjectsDetails({Key key}) : super(key: key);
      @override
      DbObjectsDetailsState createState() => DbObjectsDetailsState();
    }
    
    class DbObjectsDetailsState extends State<DbObjectsDetails> {
      @override
      Widget build(BuildContext context) {
        throw UnimplementedError();
      }
    
      void rebuild() => setState((){})
}

推荐阅读