0

I'm new to Flutter, and I want to insert the data retrieved by an API into string variables for use in another function. Thanks for your help

my code is :------------

import 'dart:convert' as convert;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main(){

  var infos;
  getData() async{
    String myUrl="https://api.jsonbin.io/b/5e1219328d761771cc8b9394";
    var req = await http.get(myUrl);
    infos = convert.jsonDecode(req.body);
    print(infos);
    return infos;
  }

  getData();

  // I want to Fetch data here in string variables


  runApp(new MaterialApp(
    title:'Fetch Data',
    home: new Scaffold(
      appBar:  AppBar(
        title: new Text('hello'),
        backgroundColor: Colors.amber,
      ),
      body: new Center(
        child: new Text('test'),
      ),
    ),
  ));
}

4 Answers 4

1

This would work perfectly, check it out:

class Person {
  final String name;
  final String education;
  final String skill;

  Person({this.name, this.education, this.skill});

  factory Person.fromJson(Map<String, dynamic> json) {
    return Person(
      name: json['name'],
      education: json['education'],
      skill: json['skill'],
    );
  }
}

class Fetch extends StatefulWidget {
  @override
  _FetchState createState() => _FetchState();
}

class _FetchState extends State<Fetch> {
  Future<Person> fetchPerson;

  Future<Person> getData() async {
    String myUrl = "https://api.jsonbin.io/b/5e1219328d761771cc8b9394";
    var response = await http.get(myUrl);
    Map<String, dynamic> responseJson = convert.jsonDecode(response.body);
    return Person.fromJson(responseJson);
  }

  @override
  void initState() {
    fetchPerson = getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text('hello'),
        backgroundColor: Colors.amber,
      ),
      body: FutureBuilder(
        future: fetchPerson,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    'Name is: ${snapshot.data.name}',
                    textAlign: TextAlign.start,
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  Text(
                    'Education is: ${snapshot.data.education}',
                    textAlign: TextAlign.start,
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  Text(
                    'Skill is: ${snapshot.data.skill}',
                    textAlign: TextAlign.start,
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            );
          } else if (snapshot.hasError) {
            Text(
              snapshot.error.toString(),
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }
}

Output: enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your help, i already realized that, what i want in my question to retrieve for example the content of the info variable in a string variable on outside of the build widget (BuildContext context)
Dont forget to upvote and accept my answer if it helps you !
0

You should use stateful widget to do it.

Following code may help you more.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(
    new MaterialApp(
      title: 'Fetch Data',
      home: Home(),
    ),
  );
}

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

class _HomeState extends State<Home> {
  @override
  void initState() {
    super.initState();
    getData().then((value) {
      setState(() {
        infos = value;
      });
    });
  }

  var infos;
  getData() async {
    String myUrl = "https://api.jsonbin.io/b/5e1219328d761771cc8b9394";
    var req = await http.get(myUrl);
    infos = json.decode(req.body);
    print(infos['name']);
    return infos['name'];
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: new Text('hello'),
        backgroundColor: Colors.amber,
      ),
      body: new Center(
        child: infos == null ? new Text('test') : Text(infos),
      ),
    );
  }
}

2 Comments

thanks for your help, i already realized that, but what i want in my question to retrieve for example the content of the info variable in a string variable on outside of the build widget (BuildContext context)
Accept my answer if you found it useful.
0

Fetch From API

import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() => runApp(MaterialApp(home: Homepage()));

class Homepage extends StatefulWidget {
  @override
  _Homepagestate createState() => _Homepagestate();
}

class _Homepagestate extends State<Homepage> {
  String Stringrespon;
  List Listresponse;
  Map Mapresponse;
  List Listfacts;

  Future fetchData() async {
    http.Response response;
    response = await http
        .get('http://example.com');
    if (response.statusCode == 200) {
      setState(() {
        Mapresponse = jsonDecode(response.body);
        Listfacts = Mapresponse['Data'];
      });
    }
  }

  @override
  void initState() {
    fetchData();
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fetch data'),
        backgroundColor: Colors.blue,
      ),
      body: Mapresponse == null
          ? Container()
          : SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  // Text(
                  //   Mapresponse['category'].toString(),
                  //   style: TextStyle(fontSize: 30),
                  // ),
                  ListView.builder(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      return Container(
                        margin: EdgeInsets.all(10),
                        child: Column(
                          children: <Widget>[
                            //Image.network(Listfacts[index]['image_url']),
                            Text(
                              Listfacts[index]['LeaveTypeName'].toString(),
                              style: TextStyle(
                                  fontSize: 24, fontWeight: FontWeight.bold),
                            ),
                            Text(
                              Listfacts[index]['CreatedDate'].toString(),
                              style: TextStyle(fontSize: 15),
                            ),
                          ],
                        ),
                      );
                    },
                    itemCount: Listfacts == null ? 0 : Listfacts.length,
                  )
                ],
              ),
            ),
    );
  }
}

Upload to Api

import 'package:flutter/material.dart';
import 'SignUp.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class Home extends StatefulWidget {
  final String username;
  Home({
    Key key,
    @required this.username,
  }) : super(key: key);

  @override
  _Login createState() => _Login();
}

class _Login extends State<Home> {
  Future upData(String reqDate, String fromdate, String todate,
      String description, int fdays, int hdays, int typeleave) async {
    var body = json.encode({
      "EmployeeId": 19,
      "LeaveTypeId": typeleave,
      "RequestDate": reqDate,
      "NoofFullDay": fdays,
      "NoofHalfDay": hdays,
      "Datefrom": fromdate,
      "Dateto": todate,
      "Description": description,
      "Status": 1,
      "CreatedBy": 20,
      "UpdatedBy": null,
      "CreatedDate": reqDate,
      "UpdatedDate": null,
      "IsDelete": false,
      "IsActive": true,
    });
    http.Response response;

   
    response = await http.post(
        "http://example.com/save",
        body: body,
        headers: {'Content-type': 'application/json'});
  }
  //call updata

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Smple Login",
      home: Scaffold(
        resizeToAvoidBottomPadding: false,
        body: Center(
          child: Container(
            child: RaisedButton(onPressed: () {
              upData(
                reqDateController.text,
                fromdateController.text,
                todateController.text,
                descriptionController.text,
                int.parse(fdaysController.text),
                int.parse(hdaysController.text),
                int.parse(_myState),
              );
            }),
          ),
        ),
      ),
    );
  }
}

Fetch With Parameter

 Future fetchData() async {
    var body =
        json.encode({"IsActive": true, "IsDelete": false, "CompanyId": 18});
    http.Response response;
    response = await http.post("http://example.com",
        body: body, headers: {'Content-type': 'application/json'});

    if (response.statusCode == 200) {
      setState(() {
        mapresponse = jsonDecode(response.body);
        listfacts = mapresponse['Data'];
      });
    }
  }

//Access listfacts[index]['Data']),

Comments

0
class LoginModel {
  String mobile;
  int cacheEmpId;
  int cacheCompId;
  String loginOTP;
  String oTPExpiredTime;
  String role;

  LoginModel({
    this.mobile,
    this.cacheEmpId,
    this.cacheCompId,
    this.loginOTP,
    this.oTPExpiredTime,
    this.role
  });

  LoginModel.fromJson(Map<String, dynamic> json) {
    mobile = json['Mobile'] ?? "";
    cacheEmpId=json['EmployeeId']??"";
    cacheCompId=json['CompanyId']??"";
    loginOTP = json['LoginOTP'] ?? "";
    oTPExpiredTime = json['OTPExpiredTime'] ?? "";
    role=json['ODRole']??"";
  }
}

// here is the model

import 'package:http/http.dart' as http;
import 'package:officediaryapp/Models/LoginModel.dart';
import 'dart:convert';
import 'package:officediaryapp/Utils/Api_Utils.dart';

class LoginService {
  bool error = false;
  bool loading = true;
  var login;
  bool loginDetailserror = false;
  bool logindtailsloading = true;

  Future<LoginModel> getLogin(dynamic input, String mob) async {
    try {
      loginDetailserror = false;

      http.Response response = await http.get(ApiUtils.loginApi + mob,
          headers: {'Content-type': 'application/json'});

      Map data = jsonDecode(response.body);
      if (data["Status"] == true) {
        login = data["Data"];

        logindtailsloading = true;
        return LoginModel.fromJson(data["Data"]);
      } else {
        throw data;
      }
    } catch (e) {
      print(e);
      logindtailsloading = false;
      loginDetailserror = true;
    }
  }
}
 //here is getapi code
import 'package:http/http.dart' as http;
import 'package:officediaryapp/Models/NoticeModel.dart';
import 'dart:convert';
import 'package:officediaryapp/Utils/Api_Utils.dart';

class NoticeService {
  bool error = false;
  bool loading = true;
  var notice;
  bool noticeDetailserror = false;
  bool noticeetailsloading = true;

  Future<void> getNotice(dynamic input) async {
    try {
      noticeDetailserror = false;

      http.Response response = await http.post(ApiUtils.noticeApi,
          body: input, headers: {'Content-type': 'application/json'});

      Map data = jsonDecode(response.body);
      if (data["Status"] == true) {
        notice = data["Data"];
        notice = notice.map((_data) {
          return new NoticeModel.fromJson(_data);
        }).toList();
        print(notice);
        noticeetailsloading = false;
      } else {
        throw data;
      }
    } catch (e) {
      print(e);
      noticeetailsloading = false;
      noticeDetailserror = true;
    }
  }
}
//here is post API code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.