Search with filter card (data from api) for Flutter

Viewed 698

I have a code with the help of which I take the data through the Get method and use this data in the cards. I highlight the cards with color depending on their condition. The problem is that I can't add a search by (item.name). But I can't do it. I found some examples but couldn't add them to my code. I will be grateful for your help. Here is my code:

import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/object_main/ObjectListGet.dart';
import 'package:flutter_app_seals/model/object_main/ServicesObjectMain.dart';
import 'package:flutter_app_seals/model/post/form_unseals.dart';
import 'package:flutter_app_seals/model/post/form_seals.dart';
import  'package:flutter_app_seals/model/setting/globalvar.dart' as global;


class JsonParseObjectSts extends StatefulWidget {
  //
  JsonParseObjectSts() : super();


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

class _JsonParseObjectsState extends State <StatefulWidget> {
  Widget build(BuildContext context) {
    var futureBuilder = new  FutureBuilder< List<ObjectListMain>>(
        future: ServicesObjectMain.getObjectMain(),
        builder: (context, snapshot)
        {
// Data is loading, you should show progress indicator to a user
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
// Data is loaded, handle it
          return ListView.builder(
            physics: BouncingScrollPhysics(),
            padding: EdgeInsets.all(40),
            itemCount: snapshot.data.length,
            itemBuilder: (_, index) {
              final item = snapshot.data[index];
              return Card(
                color: (item.sealed  == "Так") ? Colors.redAccent : Colors.greenAccent,
                margin: EdgeInsets.symmetric(vertical: 7),
                child: ListTile(
                  title: Text(
                    item.name,
                    style: TextStyle(fontSize: 30),
                  ),
                  subtitle: Text("Запломбований:${item.sealed}"),
                  leading: Icon(
                    Icons.home_outlined,
                    size: 40,
                    color: Colors.black87,
                  ),
                  onTap: () =>
                  {
                  if ('Так' == item.sealed) {
                  global.nameObj =  item.name,
                  global.sealsNumb = item.seal_number,
                  global.typesOp = 'Так',
                      Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => Unseals()),
                              )
                     }
                  else{
                    {
                      global.nameObj =  item.name,
                      global.typesOp = 'Ні',
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => Form_seals()),
                      )
                    }
                  }
                  }
                ),
              );

            },
          );
        }
    );
    return new Scaffold(
      body:Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colors.blue, Colors.white],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter),
          ),
          child: futureBuilder

      ),

    );
  }

}
And scrin :

enter image description here

Also I tried one more way, but in it there is a problem, the data which I take away from api they are duplicated. Duplicate when I go to this page or when I delete text from the search widget.

import 'package:flutter/material.dart';
import 'package:flutter_app_seals/model/post/form_unseals.dart';
import 'package:flutter_app_seals/model/post/form_seals.dart';
import  'package:flutter_app_seals/model/setting/globalvar.dart' as global;
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;



class JsonParseObjectSts extends StatefulWidget {


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

class _JsonParseObjectsState extends State <StatefulWidget> {
  TextEditingController controller = new TextEditingController();

  // Get json result and convert it to model. Then add
  Future<Null> getUserDetails() async {
    final response = await http.get(url);
    final responseJson = json.decode(response.body);

    setState(() {
      for (Map user in responseJson) {
        _userDetails.add(UserDetails.fromJson(user));
      }
    });
  }

  @override
  void initState() {
    super.initState();

    getUserDetails();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Column(
        children: <Widget>[
          new Container(
            color: Theme.of(context).primaryColor,
            child: new Padding(
              padding: const EdgeInsets.all(8.0),
              child: new Card(
                child: new ListTile(
                  leading: new Icon(Icons.search),
                  title: new TextField(
                    controller: controller,
                    decoration: new InputDecoration(
                        hintText: 'Пошук', border: InputBorder.none),
                    onChanged: onSearchTextChanged,
                  ),
                  trailing: new IconButton(icon: new Icon(Icons.cancel), onPressed: () {
                    controller.clear();
                    onSearchTextChanged('');
                  },),
                ),
              ),
            ),
          ),
          new Expanded(
            child: _searchResult.length != 0 || controller.text.isNotEmpty
                ? new ListView.builder(
              itemCount: _searchResult.length,
              itemBuilder: (context, i) {
                return new Card(
                  color: (_searchResult[i].sealed  == "Так") ? Colors.redAccent : Colors.greenAccent,
                  margin: EdgeInsets.symmetric(vertical: 7),
                  child: ListTile(
                      title: Text(
                        _searchResult[i].name,
                        style: TextStyle(fontSize: 30),
                      ),
                      subtitle: Text("Запломбований:${_searchResult[i].sealed}"),
                      leading: Icon(
                        Icons.home_outlined,
                        size: 40,
                        color: Colors.black87,
                      ),
                      onTap: () =>
                      {
                        if ('Так' == _searchResult[i].sealed) {
                          global.nameObj =  _searchResult[i].name,
                          global.sealsNumb = _searchResult[i].seal_number,
                          global.typesOp = 'Так',
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => Unseals()),
                          )
                        }
                        else{
                          {
                            global.nameObj =  _searchResult[i].name,
                            global.typesOp = 'Ні',
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => Form_seals()),
                            )
                          }
                        }
                      }
                  ),
                );
              },
            )
                : new ListView.builder(
              itemCount: _userDetails.length,
              itemBuilder: (context, index) {
                return new Card(
                  color: (_userDetails[index].sealed  == "Так") ? Colors.redAccent : Colors.greenAccent,
                  margin: EdgeInsets.symmetric(vertical: 7),
                  child: ListTile(
                      title: Text(
                        _userDetails[index].name,
                        style: TextStyle(fontSize: 30),
                      ),
                      subtitle: Text("Запломбований:${_userDetails[index].sealed}"),
                      leading: Icon(
                        Icons.home_outlined,
                        size: 40,
                        color: Colors.black87,
                      ),
                      onTap: () =>
                      {
                        if ('Так' == _userDetails[index].sealed) {
                          global.nameObj =  _userDetails[index].name,
                          global.sealsNumb = _userDetails[index].seal_number,
                          global.typesOp = 'Так',
                          Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => Unseals()),
                          )
                        }
                        else{
                          {
                            global.nameObj =  _userDetails[index].name,
                            global.typesOp = 'Ні',
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => Form_seals()),
                            )
                          }
                        }
                      }
                  ),
                );

              },
            ),
          ),
        ],
      ),
    );
  }

  onSearchTextChanged(String text) async {
    _searchResult.clear();
    if (text.isEmpty) {
      setState(() {});
      return ;
    }

    _userDetails.forEach((userDetail) {
      if (userDetail.name.contains(text) || userDetail.name.contains(text))
        _searchResult.add(userDetail);
    });

    setState(() {});
  }
}

List<UserDetails> _searchResult = [];

List<UserDetails> _userDetails = [];

final String url = global.urlVar +  '/object_status'   + '?data_area=' + global.dataArea;
class UserDetails {

  final String name, seal_number,sealed;



  UserDetails({this.name, this.sealed, this.seal_number});

  factory UserDetails.fromJson(Map<String, dynamic> json) {
    return new UserDetails(
      sealed: json['sealed'],
      name: json['name'],
      seal_number: json['seal_number'],
    );
  }
}

0 Answers
Related