0

I have a json which has a List value and I want to use this value under a gridview.builder, I tried that with a "for" it just taking first item of first list and repeat that according to lenght of related index, such as for first one (878, 878) second one (878, 878, 878) etc. What am I missing?

My goal is getting related genre ids(I will turn them names later) beside related cards but now it looks like that;

enter image description here

My code and json sample are below;

body: Container(
                    padding: EdgeInsets.all(4),
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height,
                    child: GridView.builder(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: mediaQueryData.orientation == Orientation.portrait ? 1 : 2,
                          childAspectRatio: mediaQueryData.orientation == Orientation.portrait ? MediaQuery.of(context).size.height/MediaQuery.of(context).size.width/1.05  : MediaQuery.of(context).size.width/(MediaQuery.of(context).size.height-29),
                        ),
                        itemCount: snapshot.data.results.length,
                        itemBuilder: (context, index) {
                          return
                            Padding(
                              padding: const EdgeInsets.all(3.0),
                              child: Container(
                                child: Stack(
                                  alignment: AlignmentDirectional.center,
                                  children: <Widget>[
                                    InkWell(
                                      onTap:  (){
                                        setState(() {
                                          firstRun = true;
                                          String tempName;
                                          tempName = _name;
                                          String name = "imdbid=${snapshot.data.results[index].id}&language=${AppLocalizations.of(
                                              context)
                                              .translate(
                                              'lan_code')}@$tempName";
                                          saveNamedPreference(name).then((
                                              bool committed) {Navigator.of(context).pushNamed(
                                              MovieDetailPage.routeName);
                                          });
                                        });
                                      },
                                      child: Container(
                                        width: MediaQuery.of(context).size.width,
                                        alignment: Alignment.bottomLeft,
                                        height: 245,
                                        child: Stack(
                                          alignment: Alignment.centerLeft,
                                          children: <Widget>[
                                            Card(
                                              margin: EdgeInsets.only(top: 40),
                                              elevation: 5,
                                              child: Stack(
                                                children: <Widget>[
                                                  Container(
                                                    padding:EdgeInsets.only(right:10.0),
                                                    alignment: Alignment.bottomRight,
                                                    child: CircularPercentIndicator(
                                                      radius: 40.0,
                                                      lineWidth: 5.0,
                                                      percent: snapshot.data.results[index].voteAverage/10,
                                                      center: Stack(
                                                        children: <Widget>[
                                                          Text(
                                                            snapshot.data.results[index].voteAverage.toString(),
                                                            style: TextStyle(
                                                              foreground: Paint()
                                                                ..style = PaintingStyle.stroke
                                                                ..strokeWidth = 3
                                                                ..color = Colors.black,
                                                            ),
                                                          ),
                                                          new Text(snapshot.data.results[index].voteAverage.toString(),
                                                            style: TextStyle(
                                                              fontWeight: FontWeight.bold,
                                                              color: Colors.amber,),),
                                                        ],
                                                      ),
                                                      progressColor: Colors.amber,
                                                    ),
                                                  ),
                                                  Container(
                                                    padding: mediaQueryData.orientation == Orientation.portrait ? EdgeInsets.only(left:170.0, top: 10) : EdgeInsets.only(left:140.0, top: 10),
                                                    alignment: Alignment.topLeft,
                                                    child: Column(
                                                      mainAxisAlignment: MainAxisAlignment.start,
                                                      crossAxisAlignment: CrossAxisAlignment.start,
                                                      children: <Widget>[
                                                        Text("${snapshot.data.results[index].title}",
                                                          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Theme.of(context).brightness == Brightness.dark  ? Colors.white : Colors.black,shadows: [
                                                            Shadow(color:Colors.grey,blurRadius: 0,offset: Offset(0,2)),
                                                          ]),maxLines: 3, textAlign: TextAlign.left,),
                                                        Text("(${snapshot.data.results[index].releaseDate.toString().substring(0,4)})",
                                                            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Theme.of(context).brightness == Brightness.dark  ? Colors.white : Colors.black,shadows: [
                                                              Shadow(color:Colors.grey,blurRadius: 0,offset: Offset(0,2)),
                                                            ]),maxLines: 1, textAlign: TextAlign.left),
                                                        Container(
                                                          width: 150,
                                                          height: 120,
                                                          child: GridView.builder(
                                                              shrinkWrap: true,
                                                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                                              crossAxisCount: 3,
                                                              childAspectRatio: 2/1,),
                                                            itemCount: snapshot.data.results[index].genreIds.length,
                                                            itemBuilder: (context, index) {
                                                                  for(var i = 0; i < snapshot.data.results[index].genreIds.length; i++, index++){
                                                                    print("${snapshot.data.results[index].genreIds.toString()}");
                                                                    return Text("${snapshot.data.results[index].genreIds.toString()}",);
                                                              }
                                                            return Container();}),
                                                        ),
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            Card(
                                              elevation: 3,
                                              child: Padding(
                                                padding: mediaQueryData.orientation == Orientation.portrait ? const EdgeInsets.all(6.0) : const EdgeInsets.all(4.0),
                                                child: Container(
                                                  alignment: Alignment.centerLeft,
                                                  width: mediaQueryData.orientation == Orientation.portrait ? 140 : 120,
                                                  height: 245,
                                                  child:  ClipRRect(
                                                    borderRadius: BorderRadius.circular(15.0),
                                                    child: Image.network(
                                                      snapshot.data.results[index].posterPath != null ? "http://image.tmdb.org/t/p/w500/${snapshot
                                                          .data.results[index].posterPath}" : "https://i.hizliresim.com/bbn0VB.jpg", fit: BoxFit.contain,),
                                                  ),
                                                ),
                                              ),
                                            ),

                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                        }
                    ),
                  ),
3
  • How can this work, you are using index in your itemCount but it is defined in your itemBuilder. Do you have another GridView or Listview that wraps this ? What do you want to achieve ? Do you want only all distinct genre_ids in your grid view ? Commented Apr 17, 2020 at 18:42
  • I edited my code, sorry I sent just a try, original one was as updated. when I work that print comman write list correctly I just want to add them to text widget. There is another griedview.builder around them for titles and images, full code it too long but that's relevant part. And I added an image too, I hope that would be more understandable. Commented Apr 17, 2020 at 19:12
  • Thanks that's clearer now, see my answer. Commented Apr 17, 2020 at 21:25

1 Answer 1

1

First, to avoid confusion, name your index variable differently in both builders, then you can easily see that you can use both indexes instead of the for loop :

GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
  itemCount: snapshot.data.results.length,
  itemBuilder: (context, index) {
    return GridView.builder(
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
      itemCount: snapshot.data.results[index].genreIds.length,
      itemBuilder: (context, indexGenre) {
        return Text("${snapshot.data.results[index].genreIds[indexGenre].toString()}");
      },
      return Container();
    );
  }
)

If you still want to use your loops in a more "programmative" way, then use the GridView default constructor directly (not the GridView.builder constructor) so that you can build the list of children "manually" :

GridView(
  children: <Widget>[
    for (var film in snapshot.data.results)
      GridView(
        children: <Widget>[
          for (var genre in film.genreIds)
            Text("${genre.toString()}")
        ],
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
      )
  ],
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(...),
),

Note that this last solution requires Dart > 2.3.

Sign up to request clarification or add additional context in comments.

1 Comment

That works thanks a lot, I was thinking more complex than I need, I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.