logo
down
shadow

How to filter Map in Flutter?


How to filter Map in Flutter?

By : YoTakigawa
Date : October 16 2020, 06:10 PM
wish of those help I have a json file as shown below. When user choose amount and maturity I need to show a maturity value. , This should work
code :
   final amount = "500";
   final maturity = "24M";
   _mapFastMaturity["AMOUNT"][0][amount]["MATURITY"].singleWhere((m) => m.containsKey(maturity))[maturity]
   final a = _mapFastMaturity["AMOUNT"];
   final b = a[0];
   final c = b[amount];
   final d = c["MATURITY"];
   final e = d.singleWhere((m) => m.containsKey(maturity));
   final f = e[maturity];


Share : facebook icon twitter icon
Listview filter search in Flutter

Listview filter search in Flutter


By : adi biton
Date : March 29 2020, 07:55 AM
this one helps. I've replaced hardcoded model input with getting data from url as you needed.
code :
import 'dart:async';

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() => runApp(new MaterialApp(
  home: new HomePage(),
  debugShowCheckedModeBanner: false,
));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  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(
      appBar: new AppBar(
        title: new Text('Home'),
        elevation: 0.0,
      ),
      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: 'Search', 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(
                  child: new ListTile(
                    leading: new CircleAvatar(backgroundImage: new NetworkImage(_searchResult[i].profileUrl,),),
                    title: new Text(_searchResult[i].firstName + ' ' + _searchResult[i].lastName),
                  ),
                  margin: const EdgeInsets.all(0.0),
                );
              },
            )
                : new ListView.builder(
              itemCount: _userDetails.length,
              itemBuilder: (context, index) {
                return new Card(
                  child: new ListTile(
                    leading: new CircleAvatar(backgroundImage: new NetworkImage(_userDetails[index].profileUrl,),),
                    title: new Text(_userDetails[index].firstName + ' ' + _userDetails[index].lastName),
                  ),
                  margin: const EdgeInsets.all(0.0),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

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

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

    setState(() {});
  }
}

List<UserDetails> _searchResult = [];

List<UserDetails> _userDetails = [];

final String url = 'https://jsonplaceholder.typicode.com/users';
class UserDetails {
  final int id;
  final String firstName, lastName, profileUrl;

  UserDetails({this.id, this.firstName, this.lastName, this.profileUrl = 'https://i.amz.mshcdn.com/3NbrfEiECotKyhcUhgPJHbrL7zM=/950x534/filters:quality(90)/2014%2F06%2F02%2Fc0%2Fzuckheadsho.a33d0.jpg'});

  factory UserDetails.fromJson(Map<String, dynamic> json) {
    return new UserDetails(
      id: json['id'],
      firstName: json['name'],
      lastName: json['username'],
    );
  }
}
Flutter - Filter element with same name in array

Flutter - Filter element with same name in array


By : Tom Farrow
Date : March 29 2020, 07:55 AM
I hope this helps . I have a arrays with multiple elements, some of this elements has same name and repeat through array. I need to get all elements of this array, getting only one elements of repeated elements and all non repeated elements. , This may look a bit primitive, but works as expected
code :
List list = [2, 5, 7, 9, 22, 2, 7, 5, 9, 22, 6, 4, 7, 9, 2];
List nonRepetitive = [];

for (var i = 0; i < list.length; i++) {
  bool repeated = false;
  for (var j = 0; j < nonRepetitive.length; j++) {
    if (list[i] == nonRepetitive[j]) {
      repeated = true;
    }
  }
  if (!repeated) {
    nonRepetitive.add(list[i]);
  }
}
print(nonRepetitive);
[2, 5, 7, 9, 22, 6, 4]
How to filter list in flutter?

How to filter list in flutter?


By : user3038844
Date : March 29 2020, 07:55 AM
may help you . Your productTemp is of type List but where returns Iterable. You need to turn the output of where into a List.
code :
productTemp.where((x) =>
            x.productName.toLowerCase().contains(inputText.toLowerCase())).toList();
Cannot Filter Locations In Flutter

Cannot Filter Locations In Flutter


By : user3065109
Date : March 29 2020, 07:55 AM
wish helps you First: This whole logic seems to be pretty unperformant. You are setting State on each iteration of the for loop, which causes the MapsWidget to rebuild each iteration. Why don't you create a List of Marker Items and then in the end do smth like in the following code. Additionaly i would do the something similar to the Venues:
code :
class Location {
   final Venue venue;
   final double dist;
   final int index;
   Location({this.venue, this.dist, this.index});
}

  Set<Marker> markers = Set(); //Google Maps Markers are normally a Set
  List<Location> location = List();


  Future filterMarker(_userlat, _userlong) async {
    Set<Marker> _tmpMarkers = Set();
    int filterCounter = 0;
    List<Location> _tmpLocation = List();
    for (int i = 0; i < venues.length; ++i) {
      Geolocator()
          .distanceBetween(
              _userLat, _userlong, venues[i].latitude, venues[i].longitude)
          .then((calcDist) {
        if (calcDist / 1000 < 1) {
          filterCounter++;
          final String markerIdVal = 'marker_id_$filterCounter';

          final MarkerId markerId = MarkerId(markerIdVal);

         // creating a new MARKER
         tmpMarkers.add(Marker(
           markerId: markerId,
           position: LatLng(venues[i].latitude, venues[i].longitude),
           infoWindow: InfoWindow(title: venues[i].name, snippet: '$calcDist / 1000'),
           icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
          ));
          _tmpLocation.add(Location(index: i, Venue: venue[i], dist: calcDist / 1000));
        }
      });
    }
    setState((){
     markers = _tmpMarkers;
     location = _tmpLocation;
    });
  }
// As you didn't provide any code of your bottom sheet i just call it DraggableBottomSheet
bottomSheet: DraggableBottomSheet(
   child: Column(
    children : [
      Row(
        children: [
           Text('bla'),
           Text(location.length.toString(),
             ]
        ),
      ListView.builder(
          itemCount: location.length,
          itemBuilder: (context, index) {
             return Container(
                 child Column(
                     children : [
                          Text(location[index].venue.name),
                          Text(location[index].dist.toString()),
                       ]
                 )
              );
            }
        )
     ]
   )
)

Flutter + firestore : filter list

Flutter + firestore : filter list


By : user3262723
Date : March 29 2020, 07:55 AM
I wish this helpful for you Many of the List/Iterable helper methods like map, where, expand... etc return a variant of Iterable but not List as the underlying data structure need not be a List (e.g. it can be a Set).
So most of the times, you need to call toSet or toList on the result of these methods.
code :
filteredposts = posts.where((snapshot) => snapshot.typeX == true).toList();
Related Posts Related Posts :
  • Where I can parse IoT data in Azure so I can afterwards save it to SQL DB
  • How do I display JSON data in my tableView when objects have the same value?
  • Not extracting json properly using json4s
  • Convert hashmap to simple object in Groovy
  • Break JSON in pager "less"
  • Spark How to get number of Keys changed in two JSONS in Scala?
  • read json and access multiple keys
  • can Kafka connect value conveter (JSONConverter) can be used to convert GPB?
  • Sharing Json Schema files among projects with versioning
  • Export Json data to an excel file using Angular 4
  • Return an empty array instead of null with golang for json return with gin
  • Extract Badge ID from JSON in .gitlab-ci.yml
  • Open JSON files in PhpStorm built-in web server
  • Initializing and inserting nested JSON data in Golang?
  • kubectl - format the resource quota values in json format
  • Type 'number' is not assignable to type 'string'. How to cast number to string
  • Nested json extract from powershell
  • Parsing Json using Golang
  • json_to_record with embedded encoded json in PostgreSQL >= 10
  • Incorrect type. Expected "object"
  • Extracting specific and latest data from http webserver using golang
  • How to validate JSON input in Go
  • How to get the value of a key in a JSON?
  • Storing JSON in BigQuery
  • Issue sending POST request from Swift
  • How to concat multiple fields to same line with jq
  • AWS CloudFormation Template (JSON) to Create EC2 - Unexpected Error
  • Reading JSON data for my select query in SQL Server
  • Difficulty fetching json data from API using Angular
  • How to send Map as String in POST request in flutter?
  • Getting _jsonparsefailure with valid json in logstash
  • detecting 400 response without JSON response
  • Newtonsoft deserializing Json incorrectly
  • JSON syntax for getting personal query ID
  • How to parse JSON-input
  • How to remove brakets on Json respone
  • JSON decode failed
  • Unable to render data into grid column using JSON results
  • Modifying settings.json in vscode to add shell escape flag to pdflatex in latex workshop
  • Getting key value pairs with linux server
  • Output key value pairs as JSON from T-SQL query
  • How not to allow empty fields when Unmarshalling json to a struct
  • Saving an array in JSON in ionic
  • How to return three objects into one object in java?
  • How to get json array from json object in SWIFT?
  • kubectl apply error: error converting YAML to JSON
  • .NET Core Model Not Binding
  • Convert json repsonse to strings and put it in a structure
  • How to take info from sub-object in request before validating in Django?
  • jq: concatenate two values from data set
  • How to merge data in a json by a name property in typescript
  • How do I update JSON file using PowerShell (Patch Method)
  • I can't get the data in appends with json in Laravel
  • fetching json data from local file
  • Summing JSON values
  • HTTP GET with request body to limit fields and filter
  • Angular 7 correct way to check if JSON parse returns a specific object
  • Flutter get Data from complex json
  • Remove backslashes from JSON SQL Query
  • jq: Object cannot be csv-formatted, only array
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk