flutter - StatelessWidget 中的 Futurebuilder - Flutter
问题描述
我在有状态的小部件和未来有以下代码:在 Futurebuilder 中正确调用函数 _getCategory()
class Categories extends StatefulWidget {
@override
_CategoriesState createState() => _CategoriesState();
}
class _CategoriesState extends State<Categories> {
List<AllAccounts> _allaccounts;
DatabaseHelper _dbHelper;
int _count = 0;
@override
void initState() {
super.initState();
setState(() {
_dbHelper = DatabaseHelper.instance;
});
_getCategory();
}
Future _getCategory() async {
List<AllAccounts> x = await _dbHelper.getCategory();
setState(() {
_allaccounts = x;
});
_count = _allaccounts.length;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add/Edit Categories'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 20.0,
),
Text('Select a Category', style: TextStyle(fontSize: 18.0),),
SizedBox(
height: 20.0,
),
_list(),
],
),
),
);
}
_list() =>
Expanded(
child: ListView.builder(
itemCount: _count,
itemBuilder: (context, position) {
return Card(
color: Colors.grey[600],
elevation: 2.0,
child: ListTile(
leading: Icon(Icons.group),
title: Text(_allaccounts[position].category,
style: TextStyle(fontSize: 17.0),),
trailing: Icon(Icons.arrow_forward),
onTap: (){},
),
);
},
),
);
}
但是,当我在 StatelessWidget 中尝试同样的事情时,future: in Futurebuilder 不会被调用。
class Test extends StatelessWidget {
List<AllAccounts> _allaccounts;
DatabaseHelper _dbHelper;
int _count = 0;
Future<int> _getCat() async {
List<AllAccounts> x = await _dbHelper.getCategory();
_allaccounts = x;
_count = x.length;
print(_count);
return _count;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
_list(),
],
),
),);
}
_list() => Expanded(
child: FutureBuilder<int>(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none &&
snapshot.hasData == null) {
return Center(
child: CircularProgressIndicator(),
);
}
return Container(
child: Text('Printing $_count'),
);
},
future: _getCat(),
),
);
}
Text('Printing $_count) 返回'Printing 0'。_getCat() 函数中的打印也不会显示在控制台中。
在 Stateless Widget 中使用 Futurebuilder 的方式有问题吗?
解决方案
而不是打印_count
,您需要使用snapshot.data
来获取从返回的值_getCat
。
return Container(
child: Text('Printing ${snapshot.data}'),
);
推荐阅读
- vba - 查找多个单词的任何出现并更改它们的颜色并加粗
- python - 列表理解因两个集合差异对象而失败
- css - 如何在CSS中的无缝背景图像上做等效的不透明度线性渐变
- node.js - xa如何从外部中断正在运行的嵌套循环
- c# - 如何修复'InvalidCastException:无法将'System.Int32'类型的对象转换为'System.String'类型
- go - 无法在 GORM 中设置 has-many 关联
- javascript - 为什么 catch() 块没有在 Objection.js 查询中运行,而 then() 总是运行传递 0 或 1 作为结果?
- python - 使用无服务器部署 python 保证包时出现错误“解压缩文件的大小大于 250 MB”
- javascript - XMLHttpRequest 不会抛出错误,但不会调用 onload
- asp.net-core - 如何在注入服务时将 DbContext 和实体保持在内部?