Gridview.builder doesn't update by setState()

505

Solution 1

If anyone need it, I am putting the answer here. I am using state management now and it works like a charm.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return MultiProvider(
  child: MaterialApp(
    title: 'Provider',
    home: NewMainPage(),
  ),
  providers: [
    ChangeNotifierProvider.value(value: PageState()),
  ],
);
}
}

 class PageState extends ChangeNotifier{
 var suggestionList = [

 {'name':'Domates','imageurl':'
       https://ayb.akinoncdn.com/products/2021/06/18/7025/46e
       ad09c-f4cb-4b85-acd7-8ca1d8452864_size780x780_quality60_cropCenter.jpg'},
{'name':'Biber','imageurl':'
       https://iasbh.tmgrup.com.tr/d852d6/1200/627/0/187/800/604? 
       u=https://isbh.tmgrup.com.tr/sbh/2020/05/14/biberin-faydalari-nelerdir- 
       yesil-biberin-cilde-faydalari-1589469175731.jpg'},
{'name':'Patlıcan','imageurl':'
     https://cdn.cimri.io/market/260x260/patlican-_210439.jpg'},
  ];
add(List a){
suggestionList = a.toList();
notifyListeners();
 }
}

 class NewMainPage extends StatelessWidget {

 @override
 Widget build(BuildContext context) {
 List suggestionList = Provider.of<PageState>(context).suggestionList;
 // TODO: implement build
 return Scaffold(
 appBar: AppBar(
   title: Text('Provider'),),
   body: GridView.builder(
          shrinkWrap: true,
 itemCount: Provider.of<PageState>(context).suggestionList.length,
 gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
 crossAxisCount: 2,
 ),
 itemBuilder: (context,index){
 Map data = Provider.of<PageState>(context).suggestionList[index];
 return GestureDetector(
onTap: (){
  
  Provider.of<PageState>(context,listen:false).add([{'name':'Eggplant','imageurl':'https://ayb.akinoncdn.com/products/2021/06/18/7025/46ead09c-f4cb-4b85-acd7-8ca1d8452864_size780x780_quality60_cropCenter.jpg'}].toList());
},
child:Container(

  alignment: Alignment.topLeft,
  padding: const EdgeInsets.all(8),
  decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(25),
          boxShadow: [
  BoxShadow(
    color: Colors.black.withOpacity(0.05),
    blurRadius: 2.0, // soften the shadow
    spreadRadius: 1.0, //extend the shadow
    offset: Offset(
      0, // Move to right 10  horizontally
      1.0, // Move to bottom 5 Vertically
    ),
  )
],
            


),
  child: Column(
      children: [
        Expanded(
          flex: 10,
          child: Container(
          
          decoration: BoxDecoration(
          
          borderRadius: BorderRadius.circular(25),
         
            
  image: DecorationImage(image: NetworkImage(data['imageurl']),
  fit: BoxFit.scaleDown)
),
          
        ),),
       
        Expanded(flex:1,
        child: Text(data['name'],style: TextStyle(
          fontWeight: FontWeight.w600
        ),),),
      ],
    ),
  
 ));}
   ),

 );
 }


}

Solution 2

You can try this:

    setState(() {
      suggestionList.clear();
      suggestionList= List.from(suggestionList)
       ..add({'name':'Eggplant','imageurl':'https://ayb.akinoncdn.com/products/2021/06/18/7025/46ead09c- 
 f4cb-4b85-acd7-8ca1d8452864_size780x780_quality60_cropCenter.jpg'});
    });
Share:
505
Mehmet Emre Sever
Author by

Mehmet Emre Sever

Updated on January 01, 2023

Comments

  • Mehmet Emre Sever
    Mehmet Emre Sever over 1 year

    I am creating dynamic widget from a list and When I clicked the widget that created by list I want it to update its name. I am using stateful widget and there is no error, when I click the widget suggestionList updating itself but it doesn't effect the Text widget.

    This is my list

    List suggestionList = [
    {'name':'Tomato','imageurl':'https://ayb.akinoncdn.com/products/2021/06/18/7025/46ead09c-f4cb- 
    4b85-acd7-8ca1d8452864_size780x780_quality60_cropCenter.jpg'}]; 
    

    This is my GridView

     GridView.builder(
              shrinkWrap: true,
              itemCount: suggestionList.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
         crossAxisCount: 2,
      ),
         itemBuilder: (context,index){
         Map data = suggestionList[index];
         return GestureDetector(
         onTap: (){
         setState(() {
              suggestionList.clear();
              suggestionList = 
       
       
     [{'name':'Eggplant','imageurl':'https://ayb.akinoncdn.com/products/2021/06/18/7025/46ead09c- 
     f4cb-4b85-acd7-8ca1d8452864_size780x780_quality60_cropCenter.jpg'}];
            print(suggestionList);
            });
       },
    child:Container(
    
      alignment: Alignment.topLeft,
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(25),
              boxShadow: [
      BoxShadow(
        color: Colors.black.withOpacity(0.05),
        blurRadius: 2.0, // soften the shadow
        spreadRadius: 1.0, //extend the shadow
        offset: Offset(
          0, // Move to right 10  horizontally
          1.0, // Move to bottom 5 Vertically
        ),
      )
    ],
                
    
    
    ),
      child: Column(
          children: [
            Expanded(
              flex: 10,
              child: Container(
              
              decoration: BoxDecoration(
              
              borderRadius: BorderRadius.circular(25),
             
                
      image: DecorationImage(image: NetworkImage(data['imageurl']),
      fit: BoxFit.scaleDown)
    ),
              
            ),),
           
            Expanded(flex:1,
            child: Text(data['name'],style: TextStyle(
              fontWeight: FontWeight.w600
            ),),),
          ],
        ),
      
    ));}
    ),
    
  • Mehmet Emre Sever
    Mehmet Emre Sever over 2 years
    Well it doesn't work but thank you for the care. I am using state management now and it works like a charm thank you.