Convert Future<Object> to Object model after parse json in initState flutter

34 Views Asked by At

Im new in flutter so Iam playing aroung and would be nice some hints, Illl apreciate alot. Thank you for your timeind advance. I parse data from http, so I use Future but i want to convert into real object

Data Model

class ApiService {
  Future<Survey> getSurvey() async {
    final response = await http.get(Uri.parse(ApiConstants.baseUrl));
import 'dart:convert';

class Survey {
  String id;
  String title;
  String description;
  String startedAt;
  String endedAt;
  String imageUrl;
  String termsAndConditionsUrl;
  String finishText;
  List<Question> questions;

  
  factory Survey.fromJson(Map<String, dynamic> json) => Survey(
        id: json["id"],
        title: json["title"],
        description: json["description"],
        startedAt: json["startedAt"],
        endedAt: json["endedAt"],
        imageUrl: json["imageUrl"],
        termsAndConditionsUrl: json["termsAndConditionsUrl"],
        finishText: json["finishText"],
        questions: List<Question>.from(
            json["questions"].map((x) => Question.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "title": title,
        "description": description,
        "startedAt": startedAt,
        "endedAt": endedAt,
        "imageUrl": imageUrl,
        "termsAndConditionsUrl": termsAndConditionsUrl,
        "finishText": finishText,
        "questions": List<dynamic>.from(questions.map((x) => x.toJson())),
      };
}



Data call I guess here is where I can do what I want

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:healy_app/models/constants.dart';
import 'package:healy_app/models/survey_model.dart';

class ApiService {
  Future<Survey> getSurvey() async {
    final response = await http.get(Uri.parse(ApiConstants.baseUrl));
    if (response.statusCode == 200) {
      return Survey.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
    } else {
      throw Exception('Failed to load album');
    }
  }

Page with widget where i would like to have the objet not the Future<>

import 'package:flutter/material.dart';
import 'package:healy_app/models/survey_model.dart';
import 'package:healy_app/widgets/front_accept_buttom.dart';
import 'package:healy_app/widgets/front_terms_checkbox.dart';
import 'package:healy_app/widgets/front_title.dart';
import 'package:healy_app/widgets/start_image.dart';

// ignore: must_be_immutable
class HomePage extends StatefulWidget {
  HomePage({super.key, required this.survey});
  late Future<Survey> survey;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final String appBarText = "SURVEY";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(appBarText),
        centerTitle: true,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          FutureBuilder<Survey>(
              future: widget.survey,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Column(
                    children: [
                      StartImage(url: snapshot.data!.imageUrl),
                      FrontTitle(
                        titleText: snapshot.data!.title,
                        descriptionText: snapshot.data!.description,
                      ),
                    ],
                  );
                } else if (snapshot.hasError) {
                  return Text('${snapshot.error}');
                }
                return const CircularProgressIndicator();
              }),
          const SizedBox(height: 20),
          FutureBuilder<Survey>(
              future: widget.survey,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return FrontTermsCheckbox(checkboxText: snapshot.data!.title);
                } else if (snapshot.hasError) {
                  return Text('${snapshot.error}');
                }
                return const CircularProgressIndicator();
              }),
          const SizedBox(height: 20),
          FrontAcceptButtom(
            onTap: () => Navigator.pushNamed(context, '/survey'),
          )
        ],
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:healy_app/models/api_service.dart';
import 'package:healy_app/models/survey_model.dart';
import 'package:healy_app/screens/home_page.dart';
import 'package:healy_app/screens/survey_questions.dart';

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

class App extends StatefulWidget {
  const App({super.key});

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> {
  late Future<Survey> survey;
  @override
  void initState() {
    super.initState();
    survey = ApiService().getSurvey();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (_) => HomePage(
              survey: survey,
            ),
        '/survey': (context) => QuizQuestions(
              survey: survey,
            ),
      },
    );
  }
}

0

There are 0 best solutions below