dio 类型“String”的问题不是类型转换中“Map<String, dynamic>”类型的子类型

问题描述 投票:0回答:1

我有列表视图任务和内部按钮来导航此任务的问题,但我无法显示此问题问题“dio 类型‘String’的问题不是类型转换中‘Map’类型的子类型”

我的仓库


import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:questonnaire_app/data/models/survey_data_model.dart';
import 'package:questonnaire_app/data/models/tasks_data_model.dart';
import 'package:questonnaire_app/network/dio_settings.dart';

class GetTasksRepo {
  final Dio dio = DioSettings().dio;

  Future<TasksDataModel> getTasks() async {
    try {
      final Response responce = await dio
          .get('https://getquestionnairesendpoint-nfhw57yfsq-uc.a.run.app/');
      if (responce.statusCode == 200) {
        final Map<String, dynamic> jsonResponse = jsonDecode(responce.data);
        return TasksDataModel.fromJson(jsonResponse);
      } else {
        throw Exception('Failed to load tasks');
      }
    } catch (e) {
      print('Error $e');
      rethrow;
    }
  }

  Future<SurveyDataModel> getTasksById(String id) async {
    try {
      final Response response = await dio.get(
          'https://getquestionnairesendpoint-nfhw57yfsq-uc.a.run.app/?id=$id');
      if (response.statusCode == 200) {
        print(response.data);
        final jsonResponse = response.data as Map<String, dynamic>;
        return SurveyDataModel.fromJson(jsonResponse);
      } else {
        throw Exception('Failed to load task by ID');
      }
    } catch (e) {
      print('Error $e');
      rethrow;
    }
  }
}

调查模型

class SurveyDataModel {
  String? message;
  SurveyData? data;

  SurveyDataModel({this.message, this.data});

  SurveyDataModel.fromJson(Map<String, dynamic> json) {
    message = json['message'];
    data = json['data'] != null ? SurveyData.fromJson(json['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['message'] = message;
    if (this.data != null) {
      data['data'] = this.data!.toJson();
    }
    return data;
  }
}

class SurveyData {
  String? id;
  List<Pages>? pages;

  SurveyData({this.id, this.pages});

  SurveyData.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    if (json['pages'] != null) {
      pages = <Pages>[];
      json['pages'].forEach((v) {
        pages!.add(Pages.fromJson(v as Map<String, dynamic>));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    if (pages != null) {
      data['pages'] = pages!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Pages {
  String? question;
  String? type;
  String? image;
  List<String>? options;

  Pages({this.question, this.type, this.image, this.options});

  Pages.fromJson(Map<String, dynamic> json) {
    question = json['question'];
    type = json['type'];
    image = json['image'];
    options = json['options'].cast<String>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['question'] = question;
    data['type'] = type;
    data['image'] = image;
    data['options'] = options;
    return data;
  }
}

My survey screen 
import 'package:flutter/material.dart';
import 'package:questonnaire_app/data/models/survey_data_model.dart';
import 'package:questonnaire_app/data/repositories/get_tasks_repo.dart';

class SurveyScreen extends StatefulWidget {
  final String surveyId;
  const SurveyScreen({super.key, required this.surveyId});

  @override
  State<SurveyScreen> createState() => _SurveyScreenState();
}

class _SurveyScreenState extends State<SurveyScreen> {
  late Future<SurveyDataModel> surveyDataModel;
  int currentPageIndex = 0;

  @override
  void initState() {
    super.initState();
    surveyDataModel = GetTasksRepo().getTasksById(widget.surveyId);
  }

  void nextPage(int totalPages) {
    setState(() {
      if (currentPageIndex < totalPages - 1) {
        currentPageIndex++;
      }
    });
  }

  void previousPage() {
    setState(() {
      if (currentPageIndex > 0) {
        currentPageIndex--;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Опросник',
          style: TextStyle(
            fontFamily: 'Nunito',
            fontWeight: FontWeight.w800,
            fontSize: 24,
            color: Color(0xff27272E),
          ),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(1),
          child: Container(
            color: const Color(0xff8E8E93).withOpacity(0.08),
            height: 1.0,
          ),
        ),
      ),
      body: FutureBuilder<SurveyDataModel>(
        future: GetTasksRepo().getTasksById(widget.surveyId),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (!snapshot.hasData || snapshot.data == null) {
            return Center(child: Text('Survey not found'));
          } else {
            final surveyData = snapshot.data;
            final currentPage = surveyData?.data?.pages?[currentPageIndex];

            return currentPage == null
                ? Center(child: Text('No pages available'))
                : Padding(
                    padding: EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          currentPage.question ?? "",
                          style: TextStyle(
                            fontFamily: "Nunito",
                            fontWeight: FontWeight.w800,
                            fontSize: 24,
                            color: Color(0xff27272E),
                          ),
                        ),
                        SizedBox(
                          height: 16,
                        ),
                        if (currentPage.type == "multiple-choice")
                          ListView.builder(
                            shrinkWrap: true,
                            itemCount: currentPage.options?.length ?? 0,
                            itemBuilder: (context, index) {
                              final option = currentPage.options![index];
                              return ListTile(
                                title: Text(option),
                                onTap: () {},
                              );
                            },
                          ),
                        if (currentPage.type == "checkbox")
                          ListView.builder(
                            shrinkWrap: true,
                            itemCount: currentPage.options?.length ?? 0,
                            itemBuilder: (context, index) {
                              final option = currentPage.options![index];
                              return CheckboxListTile(
                                title: Text(option),
                                value: false,
                                onChanged: (bool? value) {},
                              );
                            },
                          ),
                        if (currentPage.type == 'banner')
                          Center(
                            child: Image.network(currentPage.image ?? ""),
                          ),
                        Spacer(),
                        ElevatedButton(
                          onPressed: () {},
                          child: Text('Next'),
                        ),
                      ],
                    ),
                  );
          }
        },
      ),
    );
  }
}

我想按 id 显示调查(我的所有任务都有 id),点击我的任务后我想查看我的调查

flutter dart networking dio
1个回答
0
投票

使用

dio package
进行网络数据流传输时,无需对返回的数据(主体)进行解码,因为它纯粹是
json
格式。另一方面需要
http
来解码返回的数据。

因此,对于您的问题,只需直接从返回的数据(json)构造模型对象即可。

  if (responce.statusCode == 200) {
    return TasksDataModel.fromJson(responce.data);
  } 
© www.soinside.com 2019 - 2024. All rights reserved.