【问题标题】:Fetch data from web api in flutter在 Flutter 中从 web api 获取数据
【发布时间】:2020-08-17 23:55:56
【问题描述】:

我是 Flutter 的新手,我想将 API 检索到的数据插入到字符串变量中,以便在另一个函数中使用。 感谢您的帮助

我的代码是:------------

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'),
      ),
    ),
  ));
}

【问题讨论】:

    标签: api flutter


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      从 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,
                        )
                      ],
                    ),
                  ),
          );
        }
      }
      

      上传到 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),
                    );
                  }),
                ),
              ),
            ),
          );
        }
      }
      

      带参数获取

       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'];
            });
          }
        }
      

      //访问 listfacts[index]['Data']),

      【讨论】:

        【解决方案3】:

        这会很好,检查一下:

        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(),
                  );
                },
              ),
            );
          }
        }
        

        输出:

        【讨论】:

        • 感谢您的帮助,我已经意识到,我希望在我的问题中检索例如构建小部件(BuildContext 上下文)外部的字符串变量中的 info 变量的内容跨度>
        • 如果对你有帮助,别忘了点赞并接受我的回答!
        【解决方案4】:

        你应该使用有状态的小部件来做到这一点。

        以下代码可能对您有更多帮助。

        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),
              ),
            );
          }
        }
        

        【讨论】:

        • 感谢您的帮助,我已经意识到这一点,但我想在我的问题中检索例如信息变量的内容,例如构建小部件外部的字符串变量(BuildContext 上下文)
        • 如果您觉得有用,请接受我的回答。
        猜你喜欢
        • 2021-02-03
        • 1970-01-01
        • 2021-07-20
        • 2021-06-27
        • 1970-01-01
        • 2021-05-24
        • 2020-04-01
        • 2019-10-16
        • 2022-01-12
        相关资源
        最近更新 更多