Doubt Flutter: Listview

Asked

Viewed 235 times

-2

Good morning!

Could someone assist me in a doubt?

What am I doing:

I did a search for the user to search for an Infringement or Attachments etc in the app, and soon after the action on the keyboard I redirect it to another page (Filtroinicioview) passing the data as parameter.

onFieldSubmitted: (string) {
  Navigator.of(context).push(
    MaterialPageRoute(
      builder: (context) => FiltroinicioView(filterNomeInfracao, filterNomeAnexo),
    ),
  );
},

After redirecting the user to the View page of the infraction and searched attachments, I show the List of Infractions, and attachments,

    body: Column(
      children: <Widget>[
        Expanded(
            child: ListView.builder(
          padding: EdgeInsets.all(10.0),
          itemCount: filterNomeInfracao.length +
              filterNomeAnexo.length 
          itemBuilder: (BuildContext context, int index) {
            print(filterNomeInfracao);
            print(filterNomeAnexo);

          },

Return of Print:

[Infracao{id: null, descricao:  , codigo: INFRAÇÕES, art_ctb: null, pontuacao_id: null, observacao: null, foto: null, procedimento_id: null, categoria_id: null, created: null, modified: null, deleted: null}, Infracao{id: 34, descricao: CONFIAR/ ENTREGAR  veículo a pessoa em estado FÍSICO/ PSÍQUICO SEM CONDIÇÕES  de dirigir com segurança, codigo: 517-7_0, art_ctb: 166, pontuacao_id: 5, observacao: Conforme Resolução CONTRAN 561/2015.

 [Anexo{id: 40, nome: GESTOS DE AGENTES, conteudo: movimentos convencionais de braço, adotados exclusivamente pelos agentes de autoridades de trânsito nas vias, para orientar, indicar o direi

My doubt is how I can know now inside the itemBuilder: (Buildcontext context, int index) { which list is from Infringements and which list is attachments because I need to do an IF now or be

if(for a lista ANEXOS){
faz alguma coisa
}


if( for a lista INFRACOES){
faz alguma coisa
}

AS QUOTED IN THE COMMENTARY THE FORM MADE:

   body: Column(
          children: <Widget>[
            Expanded(
              child: ListView.builder(
                padding: EdgeInsets.all(10.0),
                itemCount: filterNomeInfracao.length,
                itemBuilder: (BuildContext context, int index) {
                  if (index < filterNomeInfracao.length) {
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.fromLTRB(0.0, 25.0, 20.0, 1.0),
                          child: ListTile(
                            title: Text(
                              'INFRAÇÕES.',
                              style: TextStyle(
                                fontSize: 28.0,
                              ),
                            ),
                          ),
                        ),
                      ],
                    );
                  }
                  return ListaInfracao(filterNomeInfracao[index]);
                },
              ),
            ),
            Expanded(
              child: ListView.builder(
                padding: EdgeInsets.all(10.0),
                itemCount: filterNomeInfracao.length,
                itemBuilder: (BuildContext context, int index) {
                  if (index < filterNomeAnexo.length) {
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.fromLTRB(0.0, 25.0, 20.0, 1.0),
                          child: ListTile(
                            title: Text(
                              'ANEXOS.',
                              style: TextStyle(
                                fontSize: 28.0,
                              ),
                            ),
                          ),
                        ),
                      ],
                    );
                  }
                  return ListaAnexos(filterNomeAnexo[index]);
                },
              ),
            ),
          ],
        ));

HOW YOU ARE BRINGING THE DATA (YOU ARE NOT RETURNING THE LIST AND THE TEXT IS DUPLICATED)

inserir a descrição da imagem aqui

2 answers

1

You are responsible for choosing what to display in each case.

Its function:

(BuildContext context, int index) {}

Receives only one index as parameter, it will vary from 0 until the value you put in itemCount (exclusively). In your case goes up to

(filterNomeInfracao.length + filterNomeAnexo.length)-1

So you should check the index value before displaying the corresponding Widget:

if(index < filterNomeAnexo.length){
Return Text('Lista Anexos');
}
return Text('Lista Infrações');

This will make the list of attachments come before the list of Breaches. To do otherwise you can check the size of the other list before.

Another option, perhaps more readable would be to make two ListView.builder(). One for the list of Annexes, and one for infringements:

body: Column(
      children: <Widget>[
        Expanded(
            child: ListView.builder(
          padding: EdgeInsets.all(10.0),
          itemCount: filterNomeInfracao.length
          itemBuilder: (BuildContext context, int index) {
            return Text(filterNomeInfracao[index]);

          })),
        Expanded(
            child: ListView.builder(
          padding: EdgeInsets.all(10.0),
          itemCount: filterNomeAnexo.length 
          itemBuilder: (BuildContext context, int index) {
            return Text(filterNomeAnexo[index]);
          })),],

Both modes will work.

  • I’m creating two new Listview.Builder() as quoted......as you can see in the code I put up there, I tried to create a new Listviewbuilder inside the same Expanded( (ie ta calling two Listview) it error in Child The argument for the named Parameter 'Child' was already specified. Try removing one of the named Arguments, or correcting one of the Names to Reference a Different named Parameter

  • If you can edit the answer from the top by putting how would two list inside the Expanded I really appreciate, I’m beginner I’m catching a lot.

  • 1

    In the code you posted there is only one Listview. Anyway, I edited the answer with the example as you suggested. Each Listview has its own Expanded. I suggest you take the official Flutter Cookbooks to study. Trying to do skipping steps can make it take longer to get what you want.

  • Thank you so much for the help friend of vdd, but I put two expanded is the way you told me to put using two Expanded He just plays one list at the bottom of the other there the whole list does not get scrolable I need to give the scrool in a list only after scrolar the other list found it hard to understand i recorded the screen to take a look: https://drive.google.com/file/d/1MikRo_ZIk-4xTg2Ooo9OwFyowDut7Mrw/view?usp=sharing

  • Did you try the first way? With the if(index<length), as requested in the question?

  • Friend, I gave CTRL+z here to go back the way I did that you quoted if(index<length) take a look at the edition I did in publishing how I did and how it is

Show 1 more comment

1

You have the possibility to join the two lists into one and work validating the data type at the time you use it.

Let’s assume you owned these two classes

class Infracao {
  Infracao({this.id, this.descricao});
  int id;
  String descricao;
}

class Multa {
  Multa({this.id, this.gravidade});
  int id;
  String gravidade;
}

Then you get the details of the violations and fines, then we can join both lists and work as follows:

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  
  List<Infracao> infracoes = [
    Infracao(id: 0, descricao: "Teste 0"),
    Infracao(id: 1, descricao: "Teste 1"),
    Infracao(id: 2, descricao: "Teste 2"),
  ];
  
  List<Multa> multas = [
    Multa(id: 0, gravidade: "Alta"),
    Multa(id: 1, gravidade: "Média"),
    Multa(id: 2, gravidade: "Baixa"),
  ];  
  
  List<dynamic> dados = [];
  
  @override
  Widget build(BuildContext context) {
    
    dados.clear();
    dados.addAll(infracoes);
    dados.addAll(multas);
    
    return ListView.builder(
      itemCount: dados.length,
      itemBuilder: (BuildContext context, int index){
        if (dados[index] is Infracao)
          return Text("Infração: "+ (dados[index] as Infracao).descricao);
        else
          return Text("Multa: "+ (dados[index] as Multa).gravidade);
      },
    );
  }
}

Note: If you are working with StatefullWidget, join the lists on initState()

Doing this way, you will only have a list and within it you treat what kind of data will be drawn using validation

if (dados[index] is Infracao)
  return Text("Infração: "+ (dados[index] as Infracao).descricao);
else
  return Text("Multa: "+ (dados[index] as Multa).gravidade);
  • Friend, thank you so much for the help, you can give an olahda in the change I made in the publication where it starts in AS QUOTED IN THE COMMENT THE WAY MADE: it is not bringing the LIST in the Return and ta duplicating the Text and using two Expanded it occurs this problem of the video: https://drive.google.com/file/d/1MikRo_ZIk-4xTg2Ooo9OwFyowDut7Mrw/view

  • Brother, do not want to put the cart in front of the donkeys... I advise you to stop what you are doing and go study a little more about the framework. You don’t know how to handle a ListView which is a very common widget in applications. I leave here an example study for you Work with long lists

  • You updated your question based on another answer. In case you are really the best to do.... And another, compare my answer and @Naslausky’s, read both, understand, compare that you should be able to mount. Your problem is the same as another question of yours that I helped you, pay attention that you get.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.