flutter 类型“({bool growable})=>List< Office>”不是类型转换中类型“List”的子类型< Office>

iyr7buue  于 2022-12-30  发布在  Flutter
关注(0)|答案(3)|浏览(119)

我目前正在通过观看Udemy的视频课程学习Flutter。
按照扬声器一步一步,我结束了一个错误,我不能摆脱.

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter JSON demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Future<OfficesList> officesList;

  @override
  void initState() {
    super.initState();
    officesList = getOfficesList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Manual JSON serialization'),
        centerTitle: true,
      ),
      body: FutureBuilder<OfficesList>(
        future: officesList,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data?.offices.length,
              itemBuilder: (context, index) {
                return Card(
                  child: ListTile(
                    title: Text('${snapshot.data?.offices[index].name}'),
                    subtitle: Text('${snapshot.data?.offices[index].adress}'),
                    leading:
                        Image.network('${snapshot.data?.offices[index].image}'),
                    isThreeLine: true,
                  ),
                );
              },
            );
          } else if (snapshot.hasError) {
            return Text(snapshot.error.toString());
          } else {
            return const Text('null');
          }
          // return const Center(
          //   child: CircularProgressIndicator(),
          // );
        },
      ),
    );
  }
}
import 'dart:convert';
import 'package:http/http.dart' as http;

class OfficesList {
  List<Office> offices;
  OfficesList({required this.offices});

  factory OfficesList.fromJson(Map<String, dynamic> json) { 
    var officesJson = json['offices'] as List;    // <-- the problem might be somewhere here 
    List<Office> officesList =
        officesJson.map((i) => Office.fromJson(i)).toList as List<Office>;

    return OfficesList(
      offices: officesList,
    );
  }
}

class Office {
  String? name;
  String? adress;
  String? image;

  Office({
    required this.name,
    required this.adress,
    required this.image,
  });

  factory Office.fromJson(Map<String, dynamic> json) {
    return Office(
        name: json['name'] as String,
        adress: json['adress'] as String,
        image: json['image'] as String);
  }
}

Future<OfficesList> getOfficesList() async {
  const url = 'https://about.google/static/data/locations.json';
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    return OfficesList.fromJson(json.decode(response.body));
  } else {
    throw Exception('Error: ${response.reasonPhrase}');
  }
}

他写代码的方式可能是问题所在,因为视频有点旧(大约1 - 2年)。
我在谷歌上搜索了这个问题,试着给List添加一些参数等等,但没有用。
会非常感激任何建议。

rbl8hiat

rbl8hiat1#

OfficesList.fromJson中,需要将toList更改为toList(),以便调用函数并实际获取列表。

class OfficesList {
  List<Office> offices;
  OfficesList({required this.offices});

  factory OfficesList.fromJson(Map<String, dynamic> json) { 
    var officesJson = json['offices'] as List;

    List<Office> officesList =
        officesJson.map((i) => Office.fromJson(i)).toList() as List<Office>;
    //                                                   ^^   

    return OfficesList(
      offices: officesList,
    );
  }
}
unguejic

unguejic2#

只需删除as List<Office>,这里是一个示例。

var officeJson = json.encode([
   {"name": "test1", "address": "address1", "image": "image1"},
   {"name": "test2", "address": "address2", "image": "image2"}
]);

List<dynamic> decodedOfficeJson = jsonDecode(officeJson);

List<Office> officesList = decodedOfficeJson.map((i) => Office.fromJson(i)).toList();
zphenhs4

zphenhs43#

**Office**构造函数中名为adress的字符串出现问题。JSON中的键名为address

它返回的是null,因为没有名为adress的键

class Office {
  String? name;
  String? adress;
  String? image;

  Office({
    required this.name,
    required this.adress, // <-- "adress" instead of "address
    required this.image,
  });

  factory Office.fromJson(Map<String, dynamic> json) {
    return Office(
        name: json['name'] as String,
        adress: json['adress'] as String, // <-- "adress" instead of "address
        image: json['image'] as String);
  }
}

相关问题