我正在尝试创建一个顶部带有数字指示器的图标,并且数字指示器通过消费者提供程序接收其数据。问题是消费者函数没有更新状态,我不明白为什么(如果我通过热重载更新状态,一切正常)。
这是我的主文件的代码:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => TestData())
// I use more providers but deleted them here for brevity
],
child: TestScreen3(),
),
);
}
}
测试屏幕 3 小部件
class TestScreen3 extends StatefulWidget {
@override
_TestScreen3State createState() => _TestScreen3State();
}
class _TestScreen3State extends State<TestScreen3> {
@override
Widget build(BuildContext context) {
final testData = Provider.of<TestData>(context);
return Scaffold(
appBar: AppBar(
title: Text('Test app 3'),
actions: [
Consumer<TestData>(builder: (_, data, __) {
return IconButton(
icon: Badge(num: data.items.length.toString()),
onPressed: () => print(data.items.length));
})
],
),
body: Center(
child: ElevatedButton(
child: Text('Increase'),
onPressed: () {
testData.addItem();
},
),
),
);
}
}
徽章小部件
class Badge extends StatelessWidget {
Badge({@required this.num});
final String num;
@override
Widget build(BuildContext context) {
return Stack(
children: [
Icon(Icons.assessment),
Positioned(
child: Container(
padding: EdgeInsets.all(2),
child: Text(
num,
style: TextStyle(fontSize: 8),
textAlign: TextAlign.center,
),
constraints: BoxConstraints(
minHeight: 12,
minWidth: 12,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.red,
),
),
),
],
);
}
}
以及我使用的数据模型
class Item {
Item(this.id);
final String id;
}
class TestData with ChangeNotifier {
List<Item> _items = [];
List<Item> get items => [..._items];
void addItem() {
_items.add(Item(DateTime.now().toString()));
}
notifyListeners();
}
导入工作正常,为简洁起见,我将它们省略了。我遵循了本教程:https://www.udemy.com/course/learn-flutter-dart-to-build-ios-android-apps/,它使用了如下所示的徽章的关键参数:
class Badge extends StatelessWidget {
const Badge({
Key key,
@required this.child,
@required this.value,
this.color,
}) : super(key: key);
final Widget child;
final String value;
final Color color;
然而,教程中没有解释 key 或 super 的使用,当我将这些参数添加到我的代码中时,它们似乎没有做出改变。
非常感谢,我可能错过了一些非常明显的东西......
答案 0 :(得分:2)
在 notifyListeners();
方法中添加 addItem()
void addItem() {
_items.add(Item(DateTime.now().toString()));
notifyListeners();
}