错误:只能在初始化程序中访问静态成员

时间:2020-07-03 10:14:58

标签: flutter dart

我是扑朔迷离的新手,试图学习在不同路径之间传递数据并进行操作。我试图制作一个计数器,该计数器从输入字段中获取初始值,然后增加或减少该值。当我使用传递给它的值初始化计数器时,就会出现错误。

import 'package:flutter/material.dart';

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

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

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
var _textController = new TextEditingController();

@override
Widget build(BuildContext context) {
  return new Scaffold(
    appBar: new AppBar(
      title: new Text("Home Page"),
    ),
    body: new ListView(
      children: <Widget>[
        new ListTile(
          title: new TextField(
            controller: _textController,
            keyboardType: TextInputType.number,
          ),
        ),
        new ListTile(
          title: new RaisedButton(
            child: new Text("Next"),
            onPressed: () {
              var route = new MaterialPageRoute(
                builder: (BuildContext context) =>
                    new NumberCounter(value: _textController.toString()),
              );
              Navigator.of(context).push(route);
            },
          ),
        ),
      ],
    ),
  );
}
}

class NumberCounter extends StatefulWidget {
final String value;

NumberCounter({Key key, this.value}) : super(key: key);

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

class _NumberCounterState extends State<NumberCounter> {
String value;
int _n;

_NumberCounterState({this.value}) {
  _n = int.parse(widget.value);
  print(_n);
}

void add() {
  setState(() {
    ++_n;
  });
  print(_n);
}

void minus() {
  setState(() {
    if (_n != 0) --_n;
  });
  print(_n);
}

@override
Widget build(BuildContext context) {
  return new Scaffold(
    appBar: new AppBar(title: new Text("Number Count")),
    body: new Container(
      child: new Center(
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new FloatingActionButton(
              heroTag: "btn2",
              onPressed: add,
              child: new Icon(
                Icons.add,
                color: Colors.black,
              ),
              backgroundColor: Colors.white,
            ),
            new Text('$_n', style: new TextStyle(fontSize: 50.0)),
            new FloatingActionButton(
              heroTag: "btn1",
              onPressed: minus,
              child: new Icon(
                  const IconData(0xe15b, fontFamily: 'MaterialIcons'),
                  color: Colors.black),
              backgroundColor: Colors.white,
            ),
          ],
        ),
      ),
    ),
  );
}
}

1 个答案:

答案 0 :(得分:0)

您可以在构造函数中初始化_n变量。 在您放置的位置,widget.value未知且不可访问。

class NumberCounter extends StatefulWidget {
  final String value;

  NumberCounter({Key key, @required this.value}) : super(key: key);

  @override
  _NumberCounterState createState() => _NumberCounterState(value: value); // pass the value here.
}

class _NumberCounterState extends State<NumberCounter> {
  String value;
  int _n;
  _NumberCounterState({this.value})
  {
    _n = int.parse(value); // Not use widget.value here, widget is not known yet. You can use it in initState but not here.
    print(_n); // show 13 as expected
  }

/* // If you want to get the value from the widget
@protected
@mustCallSuper
void initState() {
    super.initState();
    _n = int.parse(widget.value);
    print(_n);
}
*/

  void add() {
    setState(() {
      ++_n;
    });
    print(_n);
  }

  void minus() {
    setState(() {
      if (_n != 0) --_n;
    });
    print(_n);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

void main() {

  runApp(NumberCounter(value:"13"));
}