Home > front end >  flutter build only a single widget
flutter build only a single widget

Time:12-31

I have two widgets in a column. One is Text and second is TextButton. What i want that if i click on button then the Text widget rebuild only not the whole page.

I am new to flutter how can i achieve this? If i convert this to a statful widget and call setState method then whole page will be rebuild. but i want to know any trick to do rebuild only a single widget out of whole page.

class Page3 extends StatelessWidget {
  Color color = Colors.red;

  changeColor() {
    // do something to rebuild only 1st column Text not the whole page
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Page3'),
        ),
        body: Column(
          children: [
            //First widget
            Text(
              'Title',
              style: TextStyle(color: color),
            ),
            //Second widget
            TextButton(
              onPressed: () => changeColor(),
              child: Text('change color of title'),
            )
          ],
        ));
  }
}

CodePudding user response:

Please refer to below code

ValueListenableBuilder widget. It is an amazing widget. It builds the widget every time the valueListenable value changes. Its values remain synced with there listeners i.e. whenever the values change the ValueListenable listen to it. It updates the UI without using setState() or any other state management technique.

In Dart, a ValueNotifier is a special type of class that extends a ChangeNotifer . ... It can be an int , a String , a bool or your own data type. Using a ValueNotifier improves the performance of Flutter app as it can help to reduce the number times a widget gets rebuilt.

ValueListenableBuilder will listen for changes to a value notifier and automatically rebuild its children when the value changes.

For more info refer to this enter image description here

Your Screen with button pressed:enter image description here

CodePudding user response:

You need to understand how setState works. Lets assume you have a class named HomeScreen, within the homescreen you are overriding the build method to build your own widgets.

Widget build(BuildContext context){
  return Column(
    children:<Widget> [
      FirstTextWidget();
      SecondTextWidget();
      ThirdTextWidget(),
    ])
}

when you call SetState function within that "homesceeen" class, the homescreen class itself calls the build method again and all of componenets you have returned within build function get re-rendered. Every text within homescreen class gets rerendered. So whats the solution? The Solution is separate your stateful widget with different class so that only those widgets gets rerendered when needed not whole. I will prefer you to use State Management plugin like Provider, bloc etc.

  • Related