Flutter:是否可以从其他脚本中的状态运行功能

时间:2020-01-02 19:50:17

标签: android function class flutter dart

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

例如: 我有2个脚本,可以说我有main.dart和loadingScreen.dart

main.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);
   }
),
//...

loadingScreen.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?

寻求帮助!

1 个答案:

答案 0 :(得分:0)

您可以通过向小部件传递密钥,然后使用该密钥访问小部件的状态来执行此操作。 (您需要公开公开该州级课程。)

main.dart

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

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

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

免责声明

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