我只是进入Flutter,Dart和Redux。已经跟随YouTube视频修改了默认的Flutter示例以使用Redux,但对我来说还是失败了,我仍然很难理解异常并对其做出有效的反应。这是代码:
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
// following this youtube video: https://youtu.be/X8B-UzqEaWc
void main() => runApp(new MyApp());
@immutable
class AppState {
final int counter;
AppState(this.counter);
}
// actions
enum Actions { increment }
// pure function
AppState reducer(AppState prev, action) {
if(action == Actions.increment) {
return new AppState(prev.counter + 1);
}
return prev;
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData.dark(),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
final store = new Store(reducer, initialState: new AppState(0));
//print(store.state.counter); <----- Undefined class 'counter'.
@override
Widget build(BuildContext context) {
return new StoreProvider(
store: store,
child: new Scaffold(
appBar: new AppBar(
title: new Text("Flutter Redux"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new StoreConnector(
converter: (store) => store.state.counter,
builder: (context, counter) => new Text(
"$counter",
style: Theme.of(context).textTheme.display1,
)
)
],
),
),
floatingActionButton: new StoreConnector<int, VoidCallback>(
converter: (store) {
return () => store.dispatch(Actions.increment);
},
builder: (context, callback) => new FloatingActionButton(
onPressed: callback,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
)
),
);
}
}
因此,首先,当我尝试运行此代码时,我收到一个异常,指出“在构建StoreConnector(dirty)时引发了以下NoSuchMethodError:
I / flutter(20662):将getter'store'调用为null。第二个问题是为什么代码中突出显示的打印方法无法识别计数器 setter/getter ?谢谢。
最佳答案
问题是我将“dart.previewDart2”设置为true,我认为在最新的预览版本中可能搞砸了。将选项设置为false后,一切运行良好。
细节:
关于redux - 学习Flutter Redux-此代码有什么问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49635933/