【问题标题】:Expected a value of type 'int', but got one of type 'String' flutter期望一个 \'int\' 类型的值,但得到一个 \'String\' 类型的值 flutter
【发布时间】:2022-12-05 05:25:56
【问题描述】:

我正在尝试在 flutter 中构建一个简单的列表,我基于我的 flutter cookbook https://docs.flutter.dev/cookbook/networking/background-parsing 的代码,但我尝试应用 DDD,因此它在不同的类中分开。

import 'package:corsiapp/Domain/Course/course.dart';
import 'package:corsiapp/Infraestructure/remote_data_source.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //3232
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.red,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: FutureBuilder<List<Course>>(
        future: RemoteDataSourceImpl(client: http.Client()).getCoursefromAPI(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Center(
              child: Text('An error has occurred!'),
            );
          } else if (snapshot.hasData) {
            return CourseList(course: snapshot.data!);
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}

class CourseList extends StatelessWidget {
  const CourseList({super.key, required this.course});

  final List<Course> course;

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: course.length,
      itemBuilder: (context, index) {
        return Text(course[index].title);
      },
    );
  }
}

import 'package:equatable/equatable.dart';
import 'package:corsiapp/Domain/Course/lesson.dart';

class Course extends Equatable {
  const Course(
      {required this.id,
      required this.title,
      required this.urlImage,
      required this.description});

  final int id;
  final String title;
  final String urlImage;
  final String description;

  factory Course.fromJson(Map<String, dynamic> json) {
    return Course(
        id: json['id'] as int,
        title: json['title'] as String,
        urlImage: json['urlimage'] as String,
        description: json['description'] as String);
  }

  @override
  List<Object?> get props => [id, title, urlImage, description];
}
import 'dart:convert';
import 'package:corsiapp/Domain/Course/course.dart';
import 'package:http/http.dart' as http;

abstract class RemoteDataSource {
  Future<List<Course>> getCoursefromAPI();
}

class RemoteDataSourceImpl implements RemoteDataSource {
  final http.Client client;
  RemoteDataSourceImpl({required this.client});

  @override
  Future<List<Course>> getCoursefromAPI() async {
    final response = await client
        .get(Uri.parse('https://638c1e60eafd555746a0b852.mockapi.io/Course'));

    if (response.statusCode == 200) {
      return parseCourse(response.body);
    } else {
      print('Serch Local Repository');
      throw Exception();
    }
  }

  // A function that converts a response body into a List<Photo>.
  List<Course> parseCourse(String responseBody) {
    final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<Course>((json) => Course.fromJson(json)).toList();
  }
}

使用基本打印我捕获了快照的错误,该错误被预期为“int”类型的值,但得到了“String”类型的一个,在教程中他们显示了我想要显示标题列表的图片列表。

【问题讨论】:

    标签: flutter dart domain-driven-design


    【解决方案1】:

    https://638c1e60eafd555746a0b852.mockapi.io/Course 返回的 JSON 表示 id 的类型是 String 而不是 int

    尝试这个:

    factory Course.fromJson(Map<String, dynamic> json) {
      return Course(
        id: int.parse(json['id']),
        title: json['title'] as String,
        urlImage: json['urlimage'] as String,
        description: json['description'] as String,
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 2020-11-12
      • 2022-01-03
      • 2021-12-27
      • 2021-03-16
      • 2022-01-08
      • 2021-09-13
      • 2021-09-18
      • 2020-12-03
      相关资源
      最近更新 更多