Home > Enterprise >  The argument type 'Object?' can't be assigned to the parameter type 'List<Des
The argument type 'Object?' can't be assigned to the parameter type 'List<Des

Time:08-12

class Destination {
  final double lat;
  final double lng;
  final String name;
  final double distance;

  const Destination({
    required this.lat,
    required this.lng,
    required this.name,
    required this.distance,
  });

  factory Destination.fromJson(Map<String, dynamic> json) {
    return Destination(
      lat: json['lat'] as double,
      lng: json['lng'] as double,
      name: json['name'] as String,
      distance: json['distance'] as double,
    );
  }
}

here is the error

 return listViewWidget(List<Destination>.from(snapshot.data));

this my code :

import 'package:flutter/material.dart';
import 'package:flutter_sorting_location/model.dart';
import 'package:geolocator/geolocator.dart';
import 'package:flutter_sorting_location/Utils.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  double? distance;
  List<Destination> destinations = [];

  Position? _currentPosition;
  List<Destination> destinationlist = [];

  Future<List<Destination>> getData() async {
    var url = 'http://xxxxxxxxxxxxxx/flutter/getlocation.php';
    var res =
        await http.get(Uri.parse(url), headers: {"Accept": "application/json"});
    print(res.body);
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data["articles"] as List;
      print(rest);
      destinations =
          rest.map<Destination>((json) => Destination.fromJson(json)).toList();
    }
    print("List Size: ${destinations.length}");
    return destinations;
  }

  @override
  void initState() {
    _getCurrentLocation();
    super.initState();
  }

  Widget listViewWidget(List<Destination> article) {
    return Container(
      child: ListView.builder(
          itemCount: 20,
          padding: const EdgeInsets.all(2.0),
          itemBuilder: (context, position) {
            return Card(
              child: ListTile(
                title: Text(
                  '${article[position].name}',
                  style: TextStyle(
                      fontSize: 18.0,
                      color: Colors.black,
                      fontWeight: FontWeight.bold),
                ),
                leading: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: SizedBox(
                    child: article[position].name == null
                        ? Image(
                            image: AssetImage('images/no_image_available.png'),
                          )
                        : Image.network('${article[position].name}'),
                    height: 100.0,
                    width: 100.0,
                  ),
                ),
              ),
            );
          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Location sorting from current location"),
      ),
      body: FutureBuilder(
          future: getData(),
          builder: (context, snapshot) {
            if (snapshot.data != null) {
              return listViewWidget(List<Destination>.from(snapshot.data));
            } else {
              return Center(child: CircularProgressIndicator());
            }
          }),
    );
  }

  // get Current Location
  _getCurrentLocation() {
    Geolocator.getCurrentPosition(
            desiredAccuracy: LocationAccuracy.best,
            forceAndroidLocationManager: true)
        .then((Position position) {
      distanceCalculation(position);
      setState(() {
        _currentPosition = position;
      });
    }).catchError((e) {
      print(e);
    });
  }

  distanceCalculation(Position position) {
    for (var d in destinations) {
      var km = getDistanceFromLatLonInKm(
          position.latitude, position.longitude, d.lat, d.lng);
      // var m = Geolocator.distanceBetween(position.latitude,position.longitude, d.lat,d.lng);
      // d.distance = m/1000;

      //d.distance = km;
      destinationlist.add(d);
      // print(getDistanceFromLatLonInKm(position.latitude,position.longitude, d.lat,d.lng));
    }

    setState(() {
      destinationlist.sort((a, b) {
        // print("a : ${a.distance}   b : ${b.distance}");
        return a.distance.compareTo(b.distance);
      });
    });
  }
}

CodePudding user response:

this what i found:

getData() is async function. Future<List<Destination>> which is return list of Object not Map or json anymore

so when you call that function here :

 body: FutureBuilder(
          future: getData(),
          builder: (context, snapshot) {

snapshot is List<Destination> , then no need to convert to list anymore. just like below

 return listViewWidget(snapshot);

then on your listViewWidget method , changes this :

 title: Text('${article.position.name}',) // no need brackets

CodePudding user response:

I still have an error with

return listViewWidget(snapshot);

Type: AsyncSnapshot<Object?>

The argument type 'AsyncSnapshot<Object?>' can't be assigned to the parameter type 'List'.

  • Related