Фильтрация моментального снимка JSON с использованием текста в текстовом поле

#flutter

Вопрос:

Я создал представление списка, заполненное из строки JSON, полученной из веб-службы. Я хотел бы отфильтровать данные в зависимости от строки поиска, вставленной в виджет текстового поля.

Строка json будет получена в этом будущем:

 future: fetchPacientes(value)
 

Как я должен получить отфильтрованные значения из снимка в зависимости от строки, вставленной в текстовое поле?

 body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Text(
                'Patients'.tr().toString(),
                style: TextStyle(fontSize: 24.0, color: Colors.black45),
              ),
            ),
            SizedBox(
              height: 8,
            ),
            // in the build method above list
            TextField(
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(15.0),
                hintText: 'Filter by name or NHC',
              ),
              onChanged: (string) {
                print("filtering string->:"  string);

              },
            ),

            Expanded(
              child: Consumer(
                builder: (context, watch, child) {
                  var value = watch(clinicaIdStateProvider).state;

                  return Container(
                    child: FutureBuilder(
                      future: fetchPacientes(value),
                      builder: (context, snapshot) {
                      
                        if (snapshot.hasData) {
                         
                          return ListView.builder(
                            itemCount: snapshot.data.length,
                            shrinkWrap: true,
                            itemBuilder: (BuildContext context, index) {
                              Paciente paciente = snapshot.data[index];
                              return new GestureDetector(
                                onTap: () {
                                  print("paciente seleccionada nbre: "  
                                      '${paciente.nombre_completo}');
                                },
                                child: new Card(

                                  elevation: 6,
                                  child: new Container(

                                    child: Column(
                                      children: [
                                        Padding(
                                          padding: const EdgeInsets.all(8.0),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Padding(
                                                padding:
                                                    const EdgeInsets.all(8.0),
                                                child: Text(
                                                  "${paciente.apellidos}"  
                                                      ", "  
                                                      "${paciente.nombre_completo}",
                                                  style:
                                                      TextStyle(fontSize: 18),
                                                ),
                                              ),
                                              Column(
                                                children: [
                                                  Container(
                                                    decoration: BoxDecoration(
                                                        color:
                                                            AppColors.azulCapenergy,
                                                        border: Border.all(
                                                          color: AppColors
                                                              .azulCapenergy,
                                                        ),
                                                        borderRadius:
                                                            BorderRadius.all(
                                                                Radius.circular(
                                                                    20))),
                                                    child: Padding(
                                                      padding:
                                                          const EdgeInsets.all(8.0),
                                                      child: Text(
                                                        "NHC: ${paciente.NHC}",
                                                        style: TextStyle(
                                                            color: AppColors
                                                                .blancoCapenergy,
                                                            fontSize: 16),
                                                      ),
                                                    ),

                                                  ),
                                                  SizedBox(height: 3,),
                                                  FlatButton(
                                                    onPressed: (){
                                                      print("boton agenda pulsado de ${paciente.nombre_completo}");
                                                    },
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                          color:
                                                          Colors.transparent,
                                                          border: Border.all(
                                                            color: AppColors
                                                                .azulCapenergy,
                                                          ),
                                                          borderRadius:
                                                          BorderRadius.all(
                                                              Radius.circular(
                                                                  15))),
                                                      child: Padding(
                                                        padding:
                                                        const EdgeInsets.all(8.0),
                                                        child: Image.network(
                                                          'https://...iconos_app/agenda.png',
                                                          height: 25,
                                                        ),
                                                      ),

                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),

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

                        return Image.asset(
                          "assets/images/vacio.png",
                          fit: BoxFit.contain,
                        );
                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
 

Ответ №1:

используйте a TextEditingController и добавьте его в контроллер текстового поля, тогда у вас будет доступ к тексту текстового поля в любом месте, где вы хотите.

вы можете использовать его для написания метода фильтра для моментального снимка.данные или создайте карту, если количество штатов ограничено

образец

  final TextEditingController _controller = TextEditingController();

@override
  void initState() {
    _controller.addListener(_filterList);
    super.initState();
  }

body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Text(
                'Patients'.tr().toString(),
                style: TextStyle(fontSize: 24.0, color: Colors.black45),
              ),
            ),
            SizedBox(
              height: 8,
            ),
            // in the build method above list
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(15.0),
                hintText: 'Filter by name or NHC',
              ),
              onChanged: (string) {
                print("filtering string->:"  string);

              },
            ),

            Expanded(
              child: Consumer(
                builder: (context, watch, child) {
                  var value = watch(clinicaIdStateProvider).state;

                  return Container(
                    child: FutureBuilder(
                      future: fetchPacientes(value),
                      builder: (context, snapshot) {
                      
                        if (snapshot.hasData) {
                         
                          return ListView.builder(
                            itemCount: snapshot.data.length,
                            shrinkWrap: true,
                            itemBuilder: (BuildContext context, index) {
                              Paciente paciente = snapshot.data[index];
                              return new GestureDetector(
                                onTap: () {
                                  print("paciente seleccionada nbre: "  
                                      '${paciente.nombre_completo}');
                                },
                                child: new Card(

                                  elevation: 6,
                                  child: new Container(

                                    child: Column(
                                      children: [
                                        Padding(
                                          padding: const EdgeInsets.all(8.0),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Padding(
                                                padding:
                                                    const EdgeInsets.all(8.0),
                                                child: Text(
                                                  "${paciente.apellidos}"  
                                                      ", "  
                                                      "${paciente.nombre_completo}",
                                                  style:
                                                      TextStyle(fontSize: 18),
                                                ),
                                              ),
                                              Column(
                                                children: [
                                                  Container(
                                                    decoration: BoxDecoration(
                                                        color:
                                                            AppColors.azulCapenergy,
                                                        border: Border.all(
                                                          color: AppColors
                                                              .azulCapenergy,
                                                        ),
                                                        borderRadius:
                                                            BorderRadius.all(
                                                                Radius.circular(
                                                                    20))),
                                                    child: Padding(
                                                      padding:
                                                          const EdgeInsets.all(8.0),
                                                      child: Text(
                                                        "NHC: ${paciente.NHC}",
                                                        style: TextStyle(
                                                            color: AppColors
                                                                .blancoCapenergy,
                                                            fontSize: 16),
                                                      ),
                                                    ),

                                                  ),
                                                  SizedBox(height: 3,),
                                                  FlatButton(
                                                    onPressed: (){
                                                      print("boton agenda pulsado de ${paciente.nombre_completo}");
                                                    },
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                          color:
                                                          Colors.transparent,
                                                          border: Border.all(
                                                            color: AppColors
                                                                .azulCapenergy,
                                                          ),
                                                          borderRadius:
                                                          BorderRadius.all(
                                                              Radius.circular(
                                                                  15))),
                                                      child: Padding(
                                                        padding:
                                                        const EdgeInsets.all(8.0),
                                                        child: Image.network(
                                                          'https://...iconos_app/agenda.png',
                                                          height: 25,
                                                        ),
                                                      ),

                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),

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

                        return Image.asset(
                          "assets/images/vacio.png",
                          fit: BoxFit.contain,
                        );
                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),

 

Комментарии:

1. Спасибо yoy @DNS, но это всего лишь мой вопрос, как написать метод фильтра для моментального снимка, используя текстовое поле для получения строки поиска

2. это означает, что ваш вопрос является частью _filterList в моем коде, я прав?

3. Я не могу найти _filterList в вашем коде?

4. внутри initState(), строка 4

5. Да, но я имею в виду, где вы объявляете _filterList?