【问题标题】:pass a variable from a statefull widget to state将变量从有状态小部件传递到状态
【发布时间】:2021-06-29 10:09:35
【问题描述】:

我尝试传递一个变量“int counter = 0;”在状态小部件中,但我不知道为什么我无法检索它,应用程序将我返回为“Null”,但我将所有变量都传递给了构造函数,(MyHomePage 类扩展了 StatefulWidget)。

import 'package:flutter/material.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, this.counter}) : super(key: key);
  final String title;
  int counter= 0;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  void _incrementCounter() {
    setState(() {
      widget.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(
              '${widget.counter}',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

感谢您的帮助

【问题讨论】:

  • 你没有在 MyHomePage 中传递它(title: 'Flutter Demo Home Page', counter = 0 or what else you want)
  • 或在构造函数 MyHomePage({Key key, this.title, this.counter = 0}) 中定义一个默认值
  • 谢谢安娜这是解决方案,这里的代码:```class MyHomePage extends StatefulWidget { final String title;整数计数器; MyHomePage({Key key, this.title, this.counter=0 }) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); }```

标签: flutter dart


【解决方案1】:

Widgets(包括StatefulWidgets)应该始终是不可变的,不应该在其生命周期内改变。事实上,如果您尝试将非final 变量添加到StatefulWidget,您应该会看到警告,因为它是Widget 的子类型,具有@immutable 注释。

很少有任何逻辑实际上发生在StatefulWidget 子类中。相反,所有状态和相关逻辑都应该在 State 类中。

您应该像这样将counter 移动到状态类中:

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

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

class _MyHomePageState extends State<MyHomePage> {
  int counter = 0;

  void _incrementCounter() {
    setState(() {
      counter++;
    }); 
  }

  // the rest is the same, except using counter instead of widget.counter
}

【讨论】:

    【解决方案2】:

    让我们先分析一下代码

    
     home: MyHomePage(title: 'Flutter Demo Home Page'),
     // You did not pass integer to the counter field, dart pass null to counter field
    
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title, this.counter
    /* here null will be initialized to the counter field */
    }) : super(key: key);
      final String title;
      int counter= 0; // now it is null
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    

    因此,您会得到 null

    如何正确传入你的场景:

    import 'package:flutter/material.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, this.counter=0}) : super(key: key);
      final String title;
      int counter;
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
      void _incrementCounter() {
        setState(() {
          widget.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(
                  '${widget.counter}',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多