I have problem with async-await. (I am not very good at programming, but learning by creating random apps...)
Problem: Using dio to get data from Node.js json-server, but I cant transform data from
Future to List. Error: type 'Future' is not a subtype of type 'List' at line 13.
List<Routes> routes = _getData();
I have read a lot of discussions here on stackoverflow and many other websites, but I just can't make it work. :( So here I am asking with specific code.
Needed code:
- Code where error appears (route_list_screen.dart)
import 'package:falcoo/api/api.dart';
import 'package:flutter/material.dart';
import 'package:falcoo/models/routes.dart';
class RouteList extends StatefulWidget {
const RouteList({Key? key}) : super(key: key);
@override
State<RouteList> createState() => _RouteListState();
}
List<Routes> routes = _getData();
class _RouteListState extends State<RouteList> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Výber trasy'),
automaticallyImplyLeading: true,
centerTitle: true,
),
body: ListView.separated(
itemCount: routes.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(routes[index].number),
subtitle: Text(routes[index].routeType),
trailing: const Text('??/??'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RouteSelected(
passedRoutes: routes[index],
),
),
);
},
);
},
separatorBuilder: (context, index) {
return const Divider();
},
),
);
}
}
_getData() async {
Future<dynamic> futureOfRoutes = getRouteList(856);
List<dynamic> routes = await futureOfRoutes;
return routes;
}
- Connecting to server (api.dart)
import 'package:falcoo/models/routes.dart';
const _url = 'http://10.0.2.2:3000/routes';
getRouteList(int driverId) async {
Response response;
var dio = Dio(BaseOptions(
responseType: ResponseType.plain,
));
response = await dio.get(_url, queryParameters: {"driver_id": driverId});
final data = routesFromJson(response.data);
return data;
}
List with param Routes = Routes is model from app.quicktype.io
CodePudding user response:
_getData()
returns a future, you can't direct assign it on List<Routes>
where it is Future<dynamic>
.
You can use initState
class _RouteListState extends State<RouteList> {
List<Routes>? routes;
_loadData() async {
routes = await _getData();
setState(() {});
}
@override
void initState() {
super.initState();
_loadData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: routes == null
? Text("On Future ....")
: ListView.separated(
itemCount: routes?.length??0,
itemBuilder: (context, index) {
return ListTile(
title: Text(routes![index].number),
subtitle: Text(routes![index].routeType),
trailing: const Text('??/??'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RouteSelected(
passedRoutes: routes![index],
),
),
);
},
);
},
separatorBuilder: (context, index) {
return const Divider();
},
),
);
}
}
Also check FutureBuilder