Flutter 动态搜索 appBar

Flutter Dynamic Searching appBar

我正在尝试在 appBar 中创建动态搜索,但不幸的是我没有成功,而且我在这一行上有错误。

results = _listPlaces.where((places) => places["place"].toLowerCase().contains(enteredKeyword.toLowerCase())

完整代码:

import 'package:favspot/src/views/places_card.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../services/places.dart';
import 'dart:async';

class SeachPlaces extends StatefulWidget {

  @override
  State<SeachPlaces> createState() => _SeachPlacesState();
}

class _SeachPlacesState extends State<SeachPlaces> {
  List<Object> _listPlaces = [];
  List<Object> _searchSearch = [];

  @override
  initState(){
    _searchSearch = _listPlaces;
    super.initState();
  }

  void _runFilter(String enteredKeyword) {
    List<Object> results = [];
    if (enteredKeyword.isEmpty) {
      results = _listPlaces;
    } else {
      results = _listPlaces.where((places) => places["place"].toLowerCase().contains(enteredKeyword.toLowerCase())
      ).toList();

      setState((){
        _searchSearch = results;
      });
    }
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    getPlacesList();
  }

  TextEditingController? _textEditngController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Container(
          width: double.infinity,
        height: 40,
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(30)),
        child: Center(
          child:TextField(
            onChanged: (value) => _runFilter(value),
            controller: _textEditngController,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.all(5),
              prefixIcon: Icon(Icons.search),
              suffix: IconButton(
                icon: Icon(Icons.clear),
                onPressed: null,
          ),
            hintText: 'Searching...',
            border: InputBorder.none,
          ),
          ),
        ),
      ),
      ),
      body: SafeArea(
        child: ListView.builder(
            itemCount: _searchSearch.length,
            itemBuilder: (context, index) {
              return PlacesCard(_searchSearch[index] as Places);
            },
        )
      ),
    );
  }

  Future getPlacesList() async {
    var data = await FirebaseFirestore.instance
        .collection('places')
        .orderBy('city', descending: false)
        .get();

    setState(() {
      _listPlaces = List.from(data.docs.map((doc) => Places.fromSnapshot(doc)));
    });
  }
}

这里是 class 个地方

class Places {
  String? place;
  String? city;
  String? status;

  Places();


    Map<String, dynamic> toJson() => {

      'city'    : city,
      'status'  : status,
    };

  Places.fromSnapshot(snapshot) :
        place = snapshot.id,
        city = snapshot.data()['city'],
        status = snapshot.data()['status'];
}

考虑使用 List<Places> _listPlaces 而不是 List<Object> _listPlaces,这样您就可以像这样访问属性:

results = _listPlaces.where((places) => places.place != null && places.place!.toLowerCase().contains(enteredKeyword.toLowerCase())
).toList();