gpt4 book ai didi

dart - flutter scoped_model : Is it possible to pass data to a field of a model class?

转载 作者:IT王子 更新时间:2023-10-29 06:51:56 24 4
gpt4 key购买 nike

是否可以将数据传递到模型类的字段?从 onPressed 方法说起。它不接受带有参数 'onPressed: model.setNumber(25)' 的 onPressed 函数,或者有什么方法可以做到这一点? 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),
),
),
);
}
}

最佳答案

你可以将你的 onPressed 包裹在一个闭包中,如下所示:

 onPressed: () => model.setNumber(25),

关于dart - flutter scoped_model : Is it possible to pass data to a field of a model class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49925249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com