我刚刚接触 Flutter、Dart 和 Redux。按照 YouTube 视频修改默认的 Flutter 示例以使用 Redux,但它对我来说失败了,我仍然很难理解异常并有效地对它们使用react。这是代码:
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),
),
)
),
);
}
}
所以首先,当我尝试运行它时,我收到一个异常,指出“以下 NoSuchMethodError 被抛出构建 StoreConnector(脏): I/flutter (20662): getter 'store' was called on null."。第二个问题是为什么代码中突出显示的打印方法无法识别计数器 getter?谢谢。
最佳答案
问题是我将“dart.previewDart2”设置为 true,我猜想在最新的预览版本中可能出现了问题。将选项设置为 false 后,一切正常。
详细信息:
- 转到文件 -> 首选项 -> 设置。
- 在搜索框中键入“dart”。
- 找到设置 dart.previewDart2 后,点击它左侧的铅笔图标并选择“复制到设置”。
- 在用户设置的右侧,将设置设为 true。
关于redux - 学习 Flutter Redux - 这段代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49635933/