簡體   English   中英

將變量從有狀態小部件傳遞到 state

[英]pass a variable from a statefull widget to state

我嘗試傳遞一個變量“int counter = 0;” 在 state 小部件中,但我不知道為什么我無法檢索它,應用程序將我返回為“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),
      ),
    );
  }
}

謝謝您的幫助

Widget s(包括StatefulWidget s)應該始終是不可變的,不應在其生命周期內改變。 事實上,如果您嘗試向StatefulWidget添加非final變量,您應該會看到警告,因為它是Widget的子類型,具有@immutable注釋。

很少有任何邏輯實際上發生在StatefulWidget子類中。 相反,所有 state 和相關邏輯都應該在State class 中。

您應該像這樣將counter移動到 state class 中:

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
}

讓我們首先分析代碼


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM