简体   繁体   English

如何在同一 lib 文件夹中的其他 screen.dart 文件中使用 main.dart 中的 flutter 变量?

[英]How do i use flutter variables from main.dart in other screen.dart files in the same lib folder?

I wanted to create an app that randomly generates my lucky number when i press floatingActionButton.我想创建一个应用程序,当我按下 floatActionButton 时,它会随机生成我的幸运数字。 I wanted to do it within 2 dart files.. let me show you the code in dart.main and first_screen.dart.我想在 2 个 dart 文件中完成。让我向您展示 dart.main 和 first_screen.dart 中的代码。

dart.main dart.main


import 'package:demo/app_screens/first_screen.dart';
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
  debugShowCheckedModeBanner: false,
  home: MyFlutterApp()
));

class MyFlutterApp extends StatefulWidget {
  @override
  _MyFlutterAppState createState() => _MyFlutterAppState();
}

class _MyFlutterAppState extends State<MyFlutterApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.yellow,
        centerTitle: true,
        title: Text('My first App',style: TextStyle(color: Colors.black, fontSize: 25.0),),
      ),
      body: FirstScreen(),
     floatingActionButton: FloatingActionButton(
        onPressed: (){
          setState(() {
          int thatNum = generateLuckyNumber();
        });},
        child: Icon(Icons.add),
     ),
    );
  }
}

and first_screen.dart in the lib/screens directory和 lib/screens 目录中的first_screen.dart

import 'dart:math';

import 'package:flutter/material.dart';

class FirstScreen extends StatefulWidget{
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  @override
  Widget build(BuildContext context) {
    return Material(color: Colors.lightBlue,
      child: Center(
        child: Text('My lucky number is ${thatNum}',style: TextStyle(
            fontSize: 28,color: Colors.black,backgroundColor:Colors.white)),
      ),
    );
  }


}

int generateLuckyNumber() {
  var random= Random();
  int luckyNumber= random.nextInt(10);
  return luckyNumber;
}

I would like to use the varibale thatNum declared in main.dart file in the first_screen.dart file.. How do you do that?我想使用 first_screen.dart 文件中 main.dart 文件中声明的变量 thatNum .. 你是怎么做到的?

The easiest way to do this, pass the thatNum in FirstScreen constructor.要做到这一点最简单的方法,通过thatNumFirstScreen构造。 Do the required changes given below进行下面给出的所需更改

class _MyFlutterAppState extends State<MyFlutterApp> {
  int thatNum;   // <- declare thatNum in the class
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.yellow,
        centerTitle: true,
        title: Text('My first App',style: TextStyle(color: Colors.black, fontSize: 25.0),),
      ),
      body: FirstScreen(thatNum:thatNum),  // <-- pass thatNum in constructor
     floatingActionButton: FloatingActionButton(
        onPressed: (){
          setState(() {
          thatNum = generateLuckyNumber();  /* <- generateLuckyNumber and assign to thatNum */
        });},
        child: Icon(Icons.add),
     ),
    );
  }
}

In the FirstScreen declare thatNumFirstScreen声明thatNum

class FirstScreen extends StatefulWidget{
  final thatNum;   // <- declare thatNum
  FirstScreen({this.thatNum});
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

In _FirstScreenState check whether the widget.thatNum is null or not._FirstScreenState检查是否widget.thatNum为空或不是。 If it is null assign Loading text or show thatNum if not widget.thatNum is not null.如果它为空,则分配加载文本或显示thatNum如果不是小部件widget.thatNum不为空。

class _FirstScreenState extends State<FirstScreen> {
  @override
  Widget build(BuildContext context) {
    return Material(color: Colors.lightBlue,
      child: Center(
        child: Text('My lucky number is ${widget.thatNum??"Loading"}',style: TextStyle(
            fontSize: 28,color: Colors.black,backgroundColor:Colors.white)),
      ),
    );
  }
}

Note: You can also use state management solution, but the above solution solves the issue easily.注意:您也可以使用状态管理解决方案,但上述解决方案很容易解决问题。 Still, you can check state management solution here不过,您可以在此处查看状态管理解决方案

You can do this thing in two ways:你可以通过两种方式来做这件事:

  1. Pass the variables in dependency of FirstScreen.传递依赖于 FirstScreen 的变量。
  2. Use InheritedWidget.使用继承的Widget。

1. Pass the variables in dependency of FirstScreen. 1. 传递依赖于 FirstScreen 的变量。

body: FirstScreen(thatNum), // in Scaffold of main.dart file.

Use it like:像这样使用它:

class FirstScreen extends StatefulWidget{
  final thatNum;
  FirstScreen(this.thatNum);
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  @override
  Widget build(BuildContext context) {
    return Material(color: Colors.lightBlue,
      child: Center(
        child: Text('My lucky number is ${widget.thatNum} ??"Loading"}',style: TextStyle(
            fontSize: 28,color: Colors.black,backgroundColor:Colors.white)),
      ),
    );
  }
}

2. Use InheritedWidget. 2. 使用继承的Widget。

Create an InheritedWidget as follows.创建一个 InheritedWidget 如下。

class MyInheritedWidget extends InheritedWidget {
  const MyInheritedWidget({
    Key key,
    @required this.thatNum,
    @required Widget child,
  }) : assert(color != null),
       assert(child != null),
       super(key: key, child: child);

  final thatNum;

  static MyInheritedWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
  }

  @override
  bool updateShouldNotify(MyInheritedWidget old) => thatNum!= old.thatNum;
}

Change: body: FirstScreen(), to: body: MyInheritedWidget(child: FirstScreen(), thatNum:thatNum),更改: body: FirstScreen(),改为: body: MyInheritedWidget(child: FirstScreen(), thatNum:thatNum),

Now all the decendent of MyInheritedWidget will be able to access thatNum by using context like:现在 MyInheritedWidget 的所有后代都可以使用如下上下文访问 thatNum:

class _FirstScreenState extends State<FirstScreen> {
  @override
  Widget build(BuildContext context) {
    final thatNum = MyInheritedWidget.of(context).thatNum;
    return Material(color: Colors.lightBlue,
      child: Center(
        child: Text('My lucky number is $thatNum ??"Loading"}',style: TextStyle(
            fontSize: 28,color: Colors.black,backgroundColor:Colors.white)),
      ),
    );
  }
}

If you have a child Widget that needs thatNum and that child widget doesn't need to pass thatNum to any further widget then thatNum should be passed in dependency.如果您有一个需要thatNum的子 Widget 并且该子小部件不需要将thatNum传递给任何进一步的小部件,那么thatNum应该依赖传递。

If you have a long hierarchy of Widget that need this data then InheritedWidget must be used to avoid passing data in each and every child's constructor.如果您有一个很长的 Widget 层次结构需要这些数据,那么必须使用 InheritedWidget 来避免在每个孩子的构造函数中传递数据。

I hope this helps, in case of any doubt please comment.我希望这会有所帮助,如有任何疑问,请发表评论。 If this answer helps you then please accept and up-vote it.如果这个答案对您有帮助,请接受并投票。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter:如何将文件引用到 main.dart? - Flutter: How to reference files into main.dart? 如何从除 main.dart 以外的 flutter 中的其他文件中获取参考 - How to take reference from other files in flutter other than main.dart Flutter:如何将 main.dart(入口点)更改为 Flutter 中的其他页面? - Flutter: How do I change main.dart(entry point) to some other page in Flutter? 如何将 list.dart 文件中的列表数据用于 main.dart - How do I use List data from list.dart file into main.dart 无法从导入的 flutter 项目中找到 main.dart 和 lib 文件夹 - unable to find main.dart and lib folder from imported flutter project 如何修复 flutter lib/main.dart 错误 - How to fix flutter lib/main.dart errors Flutter:如何打开main.dart - Flutter: How to open main.dart ZC047B10EEEE763AFB6164E07CF1CC268Z:我更改了Z35900D987289A89A83AF101D18A9F7C3501Z入口处login.zbbbb14127678960e171777897d8739501595015950101595010150150150150101010101010101010101010101010年, - Flutter: I have changed the Dart entrypoint to Login.dart , while building apks error shows that lib\main.dart not found Flutter:找不到目标文件“lib/main.dart” - Flutter : Target file "lib/main.dart" not found 如何在我的 main.dart 文件中使用 showChoiceDialog() - how can I use showChoiceDialog() in my main.dart file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM