几天来我才刚刚起步。
我正在尝试使用提供程序模式,并发现它易于使用和理解。但是,在实施之后,我发现需要按两次按钮以更新状态。
我到处都检查过,例如双函数调用,似乎没有什么错。 这是代码。
class CounterPage extends StatelessWidget {
final changeName = TextEditingController();
final changeNumber = TextEditingController();
@override
Widget build(BuildContext context) {
final CounterBloc counterBloc = Provider.of<CounterBloc>(context);
return Scaffold(
appBar:
AppBar(
title: Text(counterBloc.name.toString()),
),
body: Container(
child: Center(
child: Column(
children: <Widget>[
Text(
counterBloc.counter.toString(),
style: TextStyle(fontSize: 62.0),
),
TextField(
controller: changeName,
),
TextField(
controller: changeNumber,
),
IncrementButton( changeNumber.text, changeName.text),
],
),
),
),
);
}
}
术语错误,使用增量按钮的目的是,只需传递两个字符串并使用提供程序将其设置为UI中的某些位置。
这是我的增量按钮的样子,没什么花哨的
class IncrementButton extends StatelessWidget{
final String name;
final String number;
IncrementButton(this.name, this.number);
@override
Widget build(BuildContext context) {
final CounterBloc counterBloc = Provider.of<CounterBloc>(context);
return FlatButton.icon(
icon: Icon(Icons.add),
label: Text("Add"),
onPressed: ()=>counterBloc.nameAndCounter(name,number),
);
}
}
这就是counterBloc的样子
import 'package:flutter/material.dart';
class CounterBloc extends ChangeNotifier{
String _counter = "10";
String _name ="Alphhit";
String get counter => _counter;
String get name => _name;
nameAndCounter( String name, String digit){
_name = name;
_counter = digit;
notifyListeners();
}
}
仅在两次按下按钮后状态才会更新并反映出来? 有人可以告诉我我在做什么错吗?
答案 0 :(得分:2)
调用IncrementButton( changeNumber.text, changeName.text,),
时,它将以以前的值开头,因此在添加新文本时必须对其进行更新。您可以使用onChanged: (_){setState(() {});
Column( children: <Widget>[
Text(
counterBloc.counter,
style: TextStyle(fontSize: 62.0),
),
TextField(
controller: changeName,
onChanged: (_){
setState(() {
});
},
),
TextField(
controller: changeNumber,
onChanged: (_){
setState(() {
});
},
),
IncrementButton( changeNumber.text, changeName.text,),
],
),
或将功能发送到按钮
class CounterPage extends StatelessWidget {
final changeName = TextEditingController();
final changeNumber = TextEditingController();
final changeName = TextEditingController();
final changeNumber = TextEditingController();
_updateData() {
Provider.of<CounterBloc>(context).nameAndCounter(changeNumber.text, changeName.text);
}
@override
Widget build(BuildContext context) {
CounterBloc counterBloc = Provider.of<CounterBloc>(context);
print(counterBloc.name);
return Scaffold(
appBar: AppBar(
title: Text(counterBloc.name),
),
body: Container(
child: Center(
child: Column(
children: <Widget>[
Text(
counterBloc.counter,
style: TextStyle(fontSize: 62.0),
),
TextField(
controller: changeName,
),
TextField(
controller: changeNumber,
),
IncrementButton(_updateData),
],
),
),
),
);
}
}
class IncrementButton extends StatelessWidget {
final Function updateData;
IncrementButton(this.updateData);
@override
Widget build(BuildContext context) {
return FlatButton.icon(
icon: Icon(Icons.add),
label: Text("Add"),
onPressed: updateData,
);
}
}