是否可以将数据传递到模型类的字段?从onPressed方法说。它不接受带参数的onPressed函数,onPressed:model.setNumber(25),'或者有没有办法做到这一点? Redux是否与此类传递数据有关?
我提供了以下代码:
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new ScopedModel<CounterModel>(
model: new CounterModel(),
child: new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.green,
),
home: new CounterHome('Scoped Model Demo'),
),
);
}
}
class CounterModel extends Model {
int myNumber = 0;
void setNumber(int number) {
myNumber = number;
notifyListeners();
}
}
class CounterHome extends StatelessWidget {
final String title;
CounterHome(this.title);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'The new number is:',
),
new ScopedModelDescendant<CounterModel>(
builder: (context, child, model) => new Text(
model.myNumber.toString(),
style: Theme.of(context).textTheme.display1),
),
],
),
),
floatingActionButton: new ScopedModelDescendant<CounterModel>(
builder: (context, child, model) => new FloatingActionButton(
onPressed: model.setNumber(25), //THIS GIVES AN ERROR
tooltip: 'new number',
child: new Icon(Icons.add),
),
),
);
}
}
答案 0 :(得分:3)
您可以将onPressed
包装在一个闭包中,如下所示:
onPressed: () => model.setNumber(25),