Я хочу создавать комментарии с индикатором refre sh, но получаю ошибку ниже: я вызываю функцию из класса modalcomments.dart, а функция находится в home.dart, если я попытаюсь добавить полную функцию в modalcomments.dart снова, я получаю следующую ошибку:
home.dart
getComments(postid) async{
await Network().getComments('post/getcomments/$postid').then((res) async {
var comments = jsonDecode(res.body);
//print(comments);
setState(() {
commentsList.clear();
commentsTimes.clear();
commentsList.addAll(comments['data']);
});
});
for (var i = 0; i < commentsList.length; i++) {
DateTime todayDate = DateTime.parse(commentsList[i]['created_at']);
//print(todayDate);
var year = todayDate.year;
var month = todayDate.month;
var day = todayDate.day;
var hour = todayDate.hour;
var ago = Jiffy(DateTime(year, month, day, hour)).fromNow();
setState(() {
commentsTimes.add(ago);
});
}
modalcomments.dart
void modalComments(context,List commentsList, List commentsTimes,postid,userid) async{
print(commentsList.length);
showModalBottomSheet(
//expand: false,
context: context,
backgroundColor: Colors.transparent,
builder: (builder) {
return Scaffold(
backgroundColor: Colors.teal,
body:Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: <Widget> [
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
margin: const EdgeInsets.all(25.0),
padding: const EdgeInsets.all(10.0),
width: 220.0,
decoration: BoxDecoration(
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.all(const Radius.circular(20.0))
),
child: GestureDetector(
child: Text("Add Comments",
),
onTap: (){
textModal(context,postid, userid);
setState(() {
check = true;
});
},
),
),
IconButton(
icon: Icon(Icons.close, color: Colors.black),
tooltip: 'like',
onPressed: () {
Navigator.of(context).pop();
},
),
]
),
Container(
height: 400,
//width: 300.0,
child:commentsList.isEmpty ? Center(child: Text('No Comments, be the first one!!'))
: RefreshIndicator(
child:ListView.builder(
itemCount: commentsList.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(commentsList[index]['comments']),
subtitle: Text("From "+commentsList[index]['users']['name']),
trailing: Text(commentsTimes[index]),
);
},
),
onRefresh: _handleRefresh,
)
)
]
)
);
}
);
}
Future<Null> _handleRefresh() async {
HomeState().getComments(278);
print("refresh");
}
Ошибка Это происходит, когда вы вызываете setState () на объект состояния для виджета, который еще не был вставлен в дерево виджетов. Нет необходимости вызывать setState () в конструкторе, так как состояние уже считается грязным при его первоначальном создании.