RangeError の原因が分からない

実現したいこと

エラーを解消したい

前提

FlutterでhttpメソッドでJSON-serverからデータを受信してListViewのモデルに表示するコードを書いていてコード自体にエラーは出ていないのですが実行するとRangeErrorと言う赤い画面のエラーが出ます。

調べたところ変数に有効な値の範囲外にある値が設定された時に表示されると言うことだったので怪しい変数は見直したのですが改善せず、元々初心者でchatGPTに書かせたコードを部分的に修正していたこともあり、どこがおかしいのか全く見当も付かなくなってしまいました。

エラーメッセージ

RangeError (index) : Invalid value: Only valid value is 0:1 see also: https://flutter.dev/docs/testing/errors

該当のソースコード

final postsProvider = FutureProvider<List<Post>>((ref) async {
final response = await http.get(Uri.parse('http://192.168.1.124:3000/posts'));
if (response.statusCode == 200) {
final List<dynamic> data = json.decode(response.body);
final List<Post> posts = data.map((item) => Post.fromJson(item)).toList();
return posts;
} else {
throw Exception('Failed to load posts');
}
});

class Post {
final String title;
final String author;

Post({required this.title, required this.author});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
title: json['title'],
author: json['author'],
);
}
}

class PostList extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final postsAsyncValue = ref.watch(postsProvider);
return Scaffold(
body: postsAsyncValue.when(
data: (posts) {
return ListView.builder(
itemBuilder: (context, index) {
final post = posts[index];
return Stack(
children: <Widget>[
Container(
margin: EdgeInsets.fromLTRB(8, 0, 8, 0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
width: 2,
color: Colors.black
),
),
child: Column(
children: [
Align(
alignment: Alignment(-0.984,-0.94),
child: Icon(Icons.star, color: Colors.grey),
),
ListTile(
title: Text(post.title,
style: TextStyle(
fontSize: 16,
color: Colors.indigo,
),
),
subtitle: Text(post.author,
style: TextStyle(
fontSize: 16,
color: Colors.indigo,
),
),
),
]
),
),
]
);
},
);
},
loading: () => Center(child: CircularProgressIndicator()),
error: (error, stackTrace) => Center(child: Text(error.toString())),
),
);
}
}

JSON server側

{
"posts": [
{ "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}### ヘディングのテキスト

コメントを投稿

0 コメント