How to Refresh Specific Widget with setState in Flutter

In this example, you will learn how to refresh specific widgets only among the entire widget trees in Flutter. The setState refresh the entire widget tree, but using StatefulBuilder() you can refresh individual widget using setState(). See the example below:

int num1 = 0;
int num2 = 0;
StatefulBuilder(builder: (context, setState){
  return ElevatedButton(
    onPressed: (){
        setState((){
            num1++;
            //will refresh content of this StatefulBuilder
        });
    }, 
    child: Text("Num One - Tow: $num1 - $num2,Increase Number One")
  );
})

Here, the setState() will refresh only content inside the StatefulBuilder(). 

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int num1 = 0;
  int num2 = 0;
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar: AppBar( 
          title: Text("Refresh State of Single Widget"),
          backgroundColor: Colors.deepPurpleAccent,
      ),
      body: Container(
        padding: EdgeInsets.all(30),
        child: Column(
            children: [
              Container(
                 child: StatefulBuilder(builder: (context, setState){
                    return ElevatedButton(
                      onPressed: (){
                          setState((){
                             num1++;
                             //will refresh content of this StatefulBuilder
                          });
                      }, 
                      child: Text("Num One - Tow: $num1 - $num2,Increase Number One")
                    );
                 })
              ),

              Container(
                 child: StatefulBuilder(builder: (context, setState){
                    return ElevatedButton(
                      onPressed: (){
                          setState((){
                             num2++;
                             //will refresh content of this StatefulBuilder
                          });
                      }, 
                      child: Text("Num One - Tow: $num1 - $num2,Increase Number Two"));
                 }),
              )
            ],
        ),
      ),
    );
  }
}

In this way, you can refresh specific widgets in Flutter. 

No any Comments on this Article


Please Wait...