首页 > 解决方案 > Flutter:是否可以从其他脚本中的状态运行函数

问题描述

所以我的问题是:是否可以在其他脚本中从状态运行函数?

例如:我有 2 个脚本,假设我有 main.dart 和 loadingScreen.dart

主要.dart

//...
OutlineButton(
   child: Text("Status", style: TextStyle(color: Colors.white, fontSize: 17), textAlign: TextAlign.center,),
   borderSide: BorderSide(color: Colors.grey[400]),
   onPressed: () async {
      Navigator.pushNamed(context, '/loadingScreen', arguments: {"text": "Checking\nstatus"});
      //...
      // <--- Here I want to run updateLoadingText from loadingScreen.dart
      Navigator.pop(context);
   }
),
//...

加载屏幕.dart

class _LoadingScreenState extends State<LoadingScreen> {
  Map data = {};
  String loadingText;

  updateLoadingText(newText){
    //...
  }

  @override
  Widget build(BuildContext context) {
    //...
    return WillPopScope(
        onWillPop: () async => false,
        child: Scaffold(
        backgroundColor: Colors.grey[800],
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              SpinKitCubeGrid(
                color: Colors.white,
                size: 80,
              ),
              SizedBox(height: 24,),
              Text(
                loadingText,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 35,                
                ),
              )
            ],
          ),
        )
      ),
    );
  }
}

是否可以在 main.dart 中运行 updateLoadingText?

谢谢帮助!

标签: androidfunctionclassflutterdart

解决方案


您可以通过将密钥传递给小部件然后使用该密钥访问小部件的状态来做到这一点。(您需要公开状态类才能执行此操作。)

主要.dart

// In the class fields
final loadingScreenKey = GlobalKey<LoadingScreenState>();

// Where you build LoadingScreen
LoadingScreen(
  key: loadingScreenKey,
  // ...
),

// Button code
OutlineButton(
   // ...
   onPressed: () async {
      // ...
      loadingScreenKey.currentState.updateLoadingText(...),
   },
),

免责声明

像这样直接从另一个小部件调用状态方法通常被认为是不好的形式,因为这会产生高度耦合和分散的意大利面条代码。因此,您应该查看一个系统,您可以通过公正的服务通知小部件进行更改。有很多方法可以做到这一点,例如使用事件总线、aChangeNotifier或使用诸如 provider 或 flutter_bloc 之类的状态管理库。


推荐阅读