下面的代码是一个例子来说明这个问题。下面的代码有效,但是以下行:
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}");
}
}
最佳答案
在创建widget时将初始值作为最终值传递给构造函数,然后从State类中获取。
关于Flutter:Widget State:这段代码安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56383204/