Flutter:小部件状态:此代码安全吗?

时间:2019-05-30 17:48:36

标签: flutter widget state

下面的代码是说明此问题的示例。下面的代码有效,但是以下行:

class WidgetCustom extends StatefulWidget {

在vsCode中用绿色下划线标出了“ WidgetCustom”,并且当光标位于其上方时,它显示以下消息: “该类(或该类继承的类)被标记为@immutable,但其一个或多个实例字段不是最终的”。

代码工作正常。

使用此代码安全吗?

有没有办法在没有警告的情况下实现这一目标?

import 'package:flutter/material.dart';

class WidgetCustom extends StatefulWidget {

  _WidgetCustomState _state;

  WidgetCustom({@required int iCount}) {
    _state = _WidgetCustomState(iCount);
  }

  @override
  State<StatefulWidget> createState() {
    return _state;
  }

  int get getIcount => _state.iCount;
}

class _WidgetCustomState extends State<WidgetCustom> {
  int iCount;

  _WidgetCustomState(this.iCount);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(children: <Widget>[
      Column(
        children: <Widget>[
          RaisedButton(
              child: const Text("Please tap me"),
              onPressed: () {
                setState(() => iCount = iCount + 1);
              }),
          SizedBox(height: 40),
          Text("Tapped $iCount Times")
        ],
      ),
    ]));
  }
}

编辑后添加main.dart

import 'package:flutter/material.dart';
import 'widgetCustom.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: 'Custom Widget Demo'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: 99);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(children: [
        _widgetCustom,
        SizedBox(height: 40),
        Text(_sMessage),
      ]),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage =
        "Value from last button click = ${_widgetCustom.getIcount}");
  }
}

2 个答案:

答案 0 :(得分:0)

更新的代码:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: MyHomePage(title: 'Custom Widget Demo'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  int _value = 99;

  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: _value, function: _update);
  }

  void _update(int value) {
    setState(() {
      _value = value;
      _widgetCustom = WidgetCustom(iCount: _value, function: _update);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Column(
        children: [
          _widgetCustom,
          SizedBox(height: 40),
          Text(_sMessage),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage = "Value from last button click = ${_value}");
  }
}

class WidgetCustom extends StatefulWidget {
  final int iCount;
  final Function function;

  WidgetCustom({@required this.iCount, this.function});

  @override
  State<StatefulWidget> createState() {
    return _WidgetCustomState();
  }
}

class _WidgetCustomState extends State<WidgetCustom> {
  int _iCount;

  @override
  void initState() {
    super.initState();
    _iCount = widget.iCount;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: <Widget>[
          Column(
            children: <Widget>[
              RaisedButton(child: const Text("Please tap me"), onPressed: (){
                _iCount = _iCount + 1;
                widget.function(_iCount);
              }),
              SizedBox(height: 40),
              Text("Tapped $_iCount Times")
            ],
          ),
        ],
      ),
    );
  }
}

答案 1 :(得分:0)

在创建小部件时将初始值作为最终值传递给构造函数,然后从State类中获取它。