如何在两个不同的文件之间传递变量并对其进行操作

How to pass variables between 2 different files and manipulate them

我正在学习 flutter,我想知道如何在 2 个不同的文件之间传递变量或方法(以添加额外的小部件)。 在我的示例中,我在创建新项目时采用了 flutter 提供的代码,在此代码中,我添加了第二个名为“second.dart”的文件,其中我在文件 main“main.dart" 我乘以 10.

main.dart

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            Container(
              child: Second(),
            ),
          ],
        ),
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}


second.dart

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

class Second extends StatefulWidget {
  @override
  _SecondState createState() => _SecondState();
}

class _SecondState extends State<Second> {
  
  int counter10 = _MyHomePageState._counter * 10;


  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
      width: 200,
      height: 300,
      child: Text('My increment * 10 : $counter10 '),
    );
  }
}

但是,我遇到了这个错误。“_MyHomePageState”以红色突出显示。

lib/second.dart:11:18: Error: Getter not found: '_MyHomePageState'. var counter10 =_MyHomePageState._counter * 10;

感谢您的帮助

您应该在代码中做到以下几点:

  1. 当我们使用下划线作为变量名的第一个字符时,表示这个变量是私有的!所以你不能在第二个小部件中使用 int counter10 = _MyHomePageState._counter * 10;

  2. 如果要将变量传递给子控件,需要创建一个构造函数,如下所示:

    class Second extends StatefulWidget {
    
      int counter;
    
      Second(this.counter);
      @override
      _SecondState createState() => _SecondState();
    }
  1. 现在您可以将 _countre 变量传递给第二个小部件:
    Container(
                  child: Second(_counter),
                ),

如果有任何问题或错误,请告诉我。

请注意,这不是我们将变量传递给其他文件或其他小部件的方式。要创建小部件,如果您想从内部操作状态,则需要在有状态或无状态之间进行选择 Second class 将其声明为有状态,但在您的情况下,您需要有一个无状态小部件。

例如:

    class Second extends StatelessWidget {
      final int counter;
    
      const Second({Key key, this.counter}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return  Container(
      color: Colors.red,
      width: 200,
      height: 300,
      child: Text('My increment * 10 : ${counter * 10} '));
      }
    }

然后像这样从你的第一个传递这个变量:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            Container(
              child: Second(counter:_counter),
            ),
          ],
        ),
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

注意:您可以通过在 类 中引用它们来共享普通变量,但它们不应该是私有的,例如在它们前面有一个 _。另一件事,即使您共享您的变量,它也不会直接对第二页产生任何影响,因为 flutter 不知道它正在发生变化,而只是将其视为一个实例。

您可以使用 类 共享静态数据: 例子

class AppStrings {
static Color appColor = Colors.blue;
} 

后来称为AppStrings.appColor