【发布时间】:2022-06-13 00:11:01
【问题描述】:
我正在尝试从虚拟 API (dummy data) 获取数据并尝试在我的颤振项目的列表视图中显示它。但我收到以下错误: 我正在学习 MobX 并实现了它,我也得到了数据,但在列表视图中显示它时遇到问题。如果有人有任何其他更好的解决方案,我也对此持开放态度,因为我正处于学习阶段。
这是我尝试过的:
import 'package:flutter/material.dart';
import 'package:todo_app/domain/todo.dart';
class ToDoPage extends StatefulWidget {
const ToDoPage({Key? key}) : super(key: key);
@override
State<ToDoPage> createState() => _ToDoPageState();
}
class _ToDoPageState extends State<ToDoPage> {
late Future<List<ToDo>> futureData;
@override
void initState() {
super.initState();
// futureData = getToDo();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<ToDo>>(
future: futureData,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<ToDo>? data = snapshot.data;
return ListView.builder(
itemCount: data!.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 75,
color: Colors.white,
child: Center(
child: Text(data[index].title),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default show a loading spinner.
return const CircularProgressIndicator();
});
}
}
Future<List<ToDo>> getToDo() async {
final Dio _dio = Dio();
final Response<List<dynamic>> response =
await _dio.get('https://jsonplaceholder.typicode.com/todos');
final data = response.data;
if (data == null) {
return List.empty();
}
final rawList = data as List;
List<ToDo> result = rawList
.map((data) => ToDo.fromJson(data as Map<String, dynamic>))
.toList();
return result;
}
}
//MobX
class EditToDoViewModel extends _ToDoStore with _$EditToDoViewModel {
EditToDoViewModel(ToDoRepository toDoRepository) : super(toDoRepository);
}
abstract class _ToDoStore with Store {
final ToDoRepository _toDoRepository ;
_ToDoStore(this._toDoRepository);
@observable
bool isLoading = false;
@observable
List<ToDo> toDoList =
List<ToDo>.of([]);
@observable
String? errorMessage;
@computed
Future <List <ToDo>> get list async {
final list = await _toDoRepository.getToDo();
return list;
}
Future <void> initToDo () async{
isLoading = true;
final list = await _toDoRepository.getToDo();
if (list == null || list.isEmpty){
errorMessage = 'There is an error';
isLoading = false;
}
toDoList = list;
}
}
【问题讨论】:
-
首先,更新依赖项中的提供程序包以支持空安全
标签: flutter api dart listview mobx