我想动态呈现一个ListView。如果列表中的值发生了变化,我必须使用IDE手动热重新加载应用程序,以便应用更改。我试过使用StreamBuilder,但是语法太复杂了。
下面是我的代码:
ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: myMap.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return myMap.values.elementAt(index) == true
? Container(
padding: EdgeInsets.only(left: 20, right: 20, top: 20),
child: Container(child: Text(myMap.keys.elementAt(index)))
: Container();
}),
我的有状态小部件:
import 'package:flutter/material.dart';
class NextWidget extends StatefulWidget {
NextWidget({Key? key}) : super(key: key);
@override
_NextWidgetState createState() => _NextWidgetState();
}
class _NextWidgetState extends State<NextWidget> {
@override
Widget build(BuildContext context) {
return Container(
child: MaterialButton(onPressed: () {
setState(() {
myMap[1] = 'Modified Value';
}
}, child: Text('Modify')),
);
}
}
有两种可能的方法:
- 从
parent widget
传递一个函数给child widget
。然后你可以用它直接改变父节点的state
:
// in parent widget define a function
void parentSetState(){
setState((){});
//also you can add your own code too
}
// then in child widget use this function
MaterialButton(onPressed: () {
setState(() {
myMap[index] = index * 2;
widget.parentSetState();
}
}, child: Text('Modify')),
- 使用
provider
等状态管理。就我个人而言,我更喜欢使用这种方法。查看此链接
当你调用Next小部件时,它会与inkwell一起换行并在inkwell下写入set state方法而不是Next小部件
InkWell(
onTap: (){
setState(() {
/// write your code
});
},
child: NextWidget(),
)