1

I want to access data from the API below.
"https://api.categen.com/api.php/recent_activity/1"
and Want to print in text. Please help me.

Moreover, there is 3 classes

Home . dart file.
DataService . dart file.
Model . dart file

I tried below code.
Home.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);
  }
}
1
  • What is the current behavior ? Commented Nov 1, 2021 at 21:20

2 Answers 2

1

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

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. 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();
      }
   );  
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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:

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-> image

Your List Widget output screen-> image

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.