我在Stateful Widget和将来的代码中包含以下代码:在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中尝试相同的操作时,futurebuilder中的future:不会被调用。
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()函数中的打印内容也不会在控制台中显示。
在无状态小部件中使用Futurebuilder的方式是否存在问题?
答案 0 :(得分:0)
您需要使用_count
来获取snapshot.data
返回的值,而不是打印_getCat
。
return Container(
child: Text('Printing ${snapshot.data}'),
);