Home > Mobile >  I want to get api data from online and want to put into a list in flutter
I want to get api data from online and want to put into a list in flutter

Time:08-10

fetchData is my function from where I call the API and put the data into an object, which is UserModel Somehow, it is working perfectly. But I want to put my data into a list because I want to make a search function where I can search by name. Look into my code, which will help you to understand.

Future<UserModel>? futureUser;
Future<UserModel>? fetchData() async {
    final response =
        await http.get(Uri.parse('https://reqres.in/api/users?page=2'));
    print('This is Response: $response');
    if (response.statusCode == 200) {
     
        // this is a way which I've tried already and it works
     // return UserModel.fromJson(jsonDecode(response.body));
    } else {
      return throw Exception('Failed to load album');
    }
  }

But I want to put the data into a list and make the search available. Like if i put some name like r a b b i, it will show the matching name from the API.

I have tried this but I am not clear about the consepet. I am not familiar with how to manipulate the JSON data in a list or object or how to convert an object into a list.

List<UserModel>? userList = [];
 Future<UserModel>? fetchData() async {
   final response =
       await http.get(Uri.parse('https://reqres.in/api/users?page=2'));
   print('This is Response: $response');
   if (response.statusCode == 200) {
    // var result= UserModel.fromJson(jsonDecode(response.body));
    // print('this is result $userList');
     return  userList.add(UserModel.fromJson(jsonDecode(response.body)));
       // this is an way which i tried already and its works
    // return UserModel.fromJson(jsonDecode(response.body));
   } else {
     return throw Exception('Failed to load album');
   }
 }

This is my whole code

import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:learning_1ui_6228/utilities/app_colors.dart';
import 'package:learning_1ui_6228/utilities/helper.dart';
import 'package:learning_1ui_6228/utilities/widgets/app_line.dart';

import 'package:learning_1ui_6228/utilities/widgets/list_tile_widget.dart';

import 'package:learning_1ui_6228/views/nav_pages/profile_page.dart';
import 'package:http/http.dart' as http;

import '../model/UserModel.dart';

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

  @override
  State<FirstScreen> createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  Future<UserModel>? futureUser;
  TextEditingController textController = TextEditingController();

  // List<UserModel> userList=[];
  @override
  void initState() {
    // searchedList = userList;
    futureUser = fetchData();
    super.initState();
  }
  List<UserModel>? userList = [];
  Future<UserModel>? fetchData() async {
    final response =
        await http.get(Uri.parse('https://reqres.in/api/users?page=2'));
    print('This is Response: $response');
    if (response.statusCode == 200) {
     // var result= UserModel.fromJson(jsonDecode(response.body));
     // print('this is result $userList');
      return  userList.add(UserModel.fromJson(jsonDecode(response.body)));
        // this is an way which i tried already and its works
     // return UserModel.fromJson(jsonDecode(response.body));
    } else {
      return throw Exception('Failed to load album');
    }
  }

  List<UserModel> searchedList = [];
  void searchUser(String enteredData){
    print('entered word   ${enteredData}');
    searchedList = [];
    for(int i=0; i<userList!.length; i  ){
      if(userList[i].data![i].firstName!.toLowerCase().contains(enteredData.toLowerCase())){
        searchedList.add(userList![i]);
      }
    }
  }





  @override
  Widget build(BuildContext context) {
    //print('user list data   $searchedList');
    return SafeArea(
      child: Scaffold(
        backgroundColor: Color(0xfff8f8fa),
        body: Column(
          children: [
            //1st Section
            Container(
              height: HelperClass.h250,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: AppColors.gradientColor,
                  ),
                  borderRadius: BorderRadius.only(
                      bottomRight: Radius.circular(HelperClass.r10),
                      bottomLeft: Radius.circular(HelperClass.r10))),
              child: Column(
                children: <Widget>[
                  //Text and cross button
                  Container(
                    margin: EdgeInsets.only(
                        left: HelperClass.w10,
                        right: HelperClass.w10,
                        top: HelperClass.h20),
                    height: HelperClass.h50,
                    // color: Colors.red,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                            child: IconButton(
                                onPressed: () {},
                                icon: Icon(
                                  Icons.clear,
                                  color: Colors.white,
                                  size: 30,
                                ))),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(right: 30),
                            alignment: Alignment.center,
                            //  color: Colors.lightBlueAccent,
                            child: Text(
                              'Search',
                              style: TextStyle(
                                  fontSize: HelperClass.t25,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: HelperClass.h25,
                  ),
                  //Search Bar
                  Container(
                    margin: EdgeInsets.only(
                        left: HelperClass.w10, right: HelperClass.w10),
                    //color: Colors.amber,
                    height: HelperClass.h70,
                    width: double.infinity,
                    child: TextField(
                      controller: textController,
                      onChanged: (name) {
                        setState(() {
                          searchUser(name);
                        });
                      },
                      decoration: InputDecoration(
                        prefix: Icon(
                          Icons.search,
                          size: 26,
                        ),
                        suffix: IconButton(
                          onPressed: () {
                            setState(() {
                              textController.clear();
                              searchedList = userList;
                            });
                          },
                          icon: Icon(
                            Icons.clear,
                            size: 26,
                          ),
                        ),
                        hintText: 'Search',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(3),
                          borderSide: BorderSide.none,
                        ),
                        filled: true,
                        fillColor: Colors.white,
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // List View
            Expanded(
              child: FutureBuilder<UserModel>(
                future: futureUser,
                  builder: (context, snapshot){
                if(snapshot.hasData){
                  return ListView.builder(
                    itemCount: snapshot.data!.data!.length,
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.all(10),
                        child: Column(
                          children: [
                            InkWell(
                              onTap: () {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => ProfilePage(
                                        userName:snapshot.data!.data![index].firstName??'',

                                        followers: snapshot.data!.data![index].id.toString(),

                                        address: snapshot.data!.data![index].email.toString(),

                                        following: snapshot.data!.data![index].lastName.toString(),
                                        imageUrl: snapshot.data!.data![index].avatar.toString(),
                                      ),
                                    ));
                              },
                              child: ListTileWidgets(
                                following: snapshot.data!.data![index].lastName.toString(),
                                address: snapshot.data!.data![index].email.toString(),
                                imageUrl:snapshot.data!.data![index].avatar.toString(),
                                name: snapshot.data!.data![index].firstName??'',
                                followersCount:
                                'Followers: ${snapshot.data!.data![index].id.toString()}',
                                iconWidget: Icon(
                                  Icons.person_add_alt_outlined,
                                  color: Colors.red,
                                  size: 25,
                                ),
                              ),
                            ),
                            AppLine(
                                paddingLeft: 10,
                                paddingRight: 10,
                                heightLine: 1,
                                lineColor: Colors.grey),
                          ],
                        ),
                      );
                    },
                  );
                }
                else if (snapshot.hasError) {
                  return Text('${snapshot.error}');
                }

                // By default, show a loading spinner.
                return Center(child: CircularProgressIndicator());
              }),
            ),
          ],
        ),
      ),
    );
  }
}

This is my UserModel class

import 'dart:convert';
UserModel userModelFromJson(String str) => UserModel.fromJson(json.decode(str));
String userModelToJson(UserModel data) => json.encode(data.toJson());
class UserModel {
  UserModel({
      this.page, 
      this.perPage, 
      this.total, 
      this.totalPages, 
      this.data, 
      this.support,});

  UserModel.fromJson(dynamic json) {
    page = json['page'];
    perPage = json['per_page'];
    total = json['total'];
    totalPages = json['total_pages'];
    if (json['data'] != null) {
      data = [];
      json['data'].forEach((v) {
        data?.add(Data.fromJson(v));
      });
    }
    support = json['support'] != null ? Support.fromJson(json['support']) : null;
  }
  int? page;
  int? perPage;
  int? total;
  int? totalPages;
  List<Data>? data;
  Support? support;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['page'] = page;
    map['per_page'] = perPage;
    map['total'] = total;
    map['total_pages'] = totalPages;
    if (data != null) {
      map['data'] = data?.map((v) => v.toJson()).toList();
    }
    if (support != null) {
      map['support'] = support?.toJson();
    }
    return map;
  }

}

Support supportFromJson(String str) => Support.fromJson(json.decode(str));
String supportToJson(Support data) => json.encode(data.toJson());
class Support {
  Support({
      this.url, 
      this.text,});

  Support.fromJson(dynamic json) {
    url = json['url'];
    text = json['text'];
  }
  String? url;
  String? text;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['url'] = url;
    map['text'] = text;
    return map;
  }

}

Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
  Data({
      this.id, 
      this.email, 
      this.firstName, 
      this.lastName, 
      this.avatar,});

  Data.fromJson(dynamic json) {
    id = json['id'];
    email = json['email'];
    firstName = json['first_name'];
    lastName = json['last_name'];
    avatar = json['avatar'];
  }
  int? id;
  String? email;
  String? firstName;
  String? lastName;
  String? avatar;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['id'] = id;
    map['email'] = email;
    map['first_name'] = firstName;
    map['last_name'] = lastName;
    map['avatar'] = avatar;
    return map;
  }

}

this is my api link https://reqres.in/api/users?page=2

CodePudding user response:

No need to add UserModel to list.

  • change this
class _FirstScreenState extends State<FirstScreen> {
  UserModel? usermodel;
  List<Data?> searchResult= [];
  • change your fetch data . this will return UserModel as result.
 Future<UserModel?> fetchData() async {
   final response =
       await http.get(Uri.parse('https://reqres.in/api/users?page=2'));
   print('This is Response: $response');
   if (response.statusCode == 200) {
     return UserModel.fromJson(jsonDecode(response.body));
   } else {
     return throw Exception('Failed to load album');
   }
 }
  • create init function to set your initial data
void initFunction() async {
 UserModel data = await fetchData();  // you have to await until get the response 

//then setState to local variable so it can display to widget
// if you skip this , your usermodel is null
 setState ({
   usermodel = data ;
 });
}

then in your initState

  @override
  void initState() {
    initFunction();
    super.initState();
  }
  • usermodel.data consist of data user. to then you can apply logic to search user from the list.
void searchUser(String enteredData){
List<Data?> temp = [];
    for(int i=0; i<usermodel.data.length; i  ){
     if(enteredData.toLowerCase() == usermodel.data[i].firstName.toLowerCase()){
        temp.add(usermodel.data[i];
      }
    }
  // you need to setState again 
    setState({
       searchResult = temp;
    });
  }
  • last in you can acces the data in userModel
 @override
  Widget build(BuildContext context) {
    //print('user list data   $searchedList');
    return SafeArea(
      child: Scaffold(
        backgroundColor: Color(0xfff8f8fa),
        body: Column(
          children: [
           Text('${usermodel.data.length}'), /// number all list user
           Text('${searchResult.length}'), /// number search user

           // now you have list all user
           // and all searched list user
          // additional, you need to add logic when query is empty 


.................

maybe there error in null-safety, please debug first.

CodePudding user response:

You can simply do this

    var myList= []; // declare an empty list
    
    if (response.statusCode == 200) {
          var result= UserModel.fromJson(jsonDecode(response.body));
          if(result != null){
            myList.clear();
            myList.addAll(result);
    }
        
       }
  • Related