简体   繁体   English

在flutter中从API访问数据

[英]Access Data from API in flutter

I want to access data from the API below.我想从下面的 API 访问数据。
"https://api.categen.com/api.php/recent_activity/1" “https://api.categen.com/api.php/recent_activity/1”
and Want to print in text.并希望以文本形式打印。 Please help me.请帮我。

Moreover, there is 3 classes此外,还有3个班级

Home .家 。 dart file.飞镖文件。
DataService .数据服务。 dart file.飞镖文件。
Model .模型 。 dart file飞镖文件

I tried below code.我试过下面的代码。
Home.dart .首页.dart

import 'dart:convert';

import 'package:categen_api_test/data_service.dart';
import 'package:categen_api_test/model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  final _dataService = DataService();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Categen API"),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text("Click me"),
          onPressed: () {
            _getlist();
          },
        ),
      ),
    );
  }

  void _getlist() async {
    final response = await _dataService.getData();
    print(response.name);
  }
}

DataService数据服务

import 'dart:convert';

import 'package:categen_api_test/model.dart';
import 'package:http/http.dart' as http;

class DataService {
  Future<ModelData> getData() async {
    final String url = "https://api.categen.com/api.php/recent_activity/1";
    final uri = Uri.https('api.categen.com', '/api.php/recent_activity/1');
    final response = await http.get(uri);
    print(response.body);

    final json = jsonDecode(response.body);
    return ModelData.fromJson(json);
  }
}

First create a model like this:首先创建一个这样的模型:

class Model {
  final String name;
  final String location;
  final String action_value;
  final String item;

  Model(this.name, this.location, this.action_value, this.item);

  List<Model> getList(json) {
    List<Model> tempList = []
    json['records'].forEach((model)=> tempList.add(
        Model(
           model["name"],
           model["location"],
           model["action_value"],
           model["item"]
         )
       )
      );
   return tempList;
  }
}

Then create a function to fetch the data:然后创建一个函数来获取数据:

Future<List<Model>> fetchData() async { 
   final response = await http.get('https://api.categen.com/api.php/recent_activity/1'); 
   if (response.statusCode == 200) { 
      return Model.getList(response.body); 
   } else { 
      throw Exception('Unable to fetch products from the REST API'); 
   } 
}

call the fetch data function in the init state of the HomePage Widget在 HomePage Widget 的 init 状态调用获取数据函数

late Future<List<Model>> futureData;
void initState() {
    super.initState();
    futureData = fetchData();
}

what is left to do now is to get your data using a FutureBuilder Widget.现在剩下要做的是使用 FutureBuilder 小部件获取数据。 and display the list of your data并显示您的数据列表

FutureBuilder<Model>(
  future: futureData,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Column(
         children: snaphot.map((e)=>Text(e.name)).toList()
      );
    } else if (snapshot.hasError) {
      return Text('${snapshot.error}');
    }
    return const CircularProgressIndicator();
  },
)

if you want to reload the data on the click of a button, then call the fetch data whenever the button is clicked and then rebuild state of the Homepage widget like shown below如果您想在单击按钮时重新加载数据,则在单击按钮时调用获取数据,然后重建主页小部件的状态,如下所示

onPressed: (){
   setState(
      (){
        futureData = fetchData();
      }
   );  
}

Try below code hope its helpful to you.试试下面的代码希望对你有帮助。 If you get data from API refer my answer here or here or here hope it's helpful to you如果你从API数据是指我的答案在这里在这里在这里希望这对您有所帮助

Create your home widget:创建您的家庭小部件:

 Center(
    child: ElevatedButton(
      child: Text('Pressed Me'),
      onPressed: () => Navigator.push(
        context,
        MaterialPageRoute(
         builder: (context) => Jobs(),
        ),
      ),
    ),
  ),

Create your List Widget.创建您的列表小部件。

Your API Call function:您的 API 调用函数:

Future<List<dynamic>> getJobsData() async {
    String url = 'https://api.categen.com/api.php/recent_activity/1';
    var response = await http.get(Uri.parse(url), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    });
    return json.decode(response.body)['records'];
  }

Your Widget:你的小部件:

Column(
    children: [
      Expanded(
        child: Center(
          child: FutureBuilder<List<dynamic>>(
            future: getJobsData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ListView.builder(
                    itemCount: snapshot.data!.length,
                    itemBuilder: (context, index) {
                      var name = snapshot.data![index]['name'];
                      var location = snapshot.data![index]['location'];
                      var item = snapshot.data![index]['item'];
                      var action = snapshot.data![index]['action_value'];
                      var date = snapshot.data![index]['created_timestamp'];
                      return Card(
                        shape: RoundedRectangleBorder(
                          side: BorderSide(color: Colors.green.shade300),
                          borderRadius: BorderRadius.circular(15.0),
                        ),
                        child: ListTile(
                          leading: Text(
                            action.toString(),
                          ),
                          title: Text(name),
                          subtitle: Text(
                            location + '\n' + date,
                          ),
                          trailing: Text(item),
                        ),
                      );
                    },
                  ),
                );
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    ],
  ),

Your all class:您的所有课程:

 class Jobs extends StatelessWidget {

  Future<List<dynamic>> getJobsData() async {
    String url = 'https://api.categen.com/api.php/recent_activity/1';
    var response = await http.get(Uri.parse(url), headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    });
    return json.decode(response.body)['records'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Jobs'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Center(
              child: FutureBuilder<List<dynamic>>(
                future: getJobsData(),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: ListView.builder(
                        itemCount: snapshot.data!.length,
                        itemBuilder: (context, index) {
                          var name = snapshot.data![index]['name'];
                          var location = snapshot.data![index]['location'];
                          var item = snapshot.data![index]['item'];
                          var action = snapshot.data![index]['action_value'];
                          var date = snapshot.data![index]['created_timestamp'];
                          return Card(
                            shape: RoundedRectangleBorder(
                              side: BorderSide(color: Colors.green.shade300),
                              borderRadius: BorderRadius.circular(15.0),
                            ),
                            child: ListTile(
                              leading: Text(
                                action.toString(),
                              ),
                              title: Text(name),
                              subtitle: Text(
                                location + '\n' + date,
                              ),
                              trailing: Text(item),
                            ),
                          );
                        },
                      ),
                    );
                  }
                  return CircularProgressIndicator();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Your Home widget output screen->您的主页小部件输出屏幕-> 图片

Your List Widget output screen->您的列表小部件输出屏幕-> 图片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM