Home > Back-end >  Widget not updating in flutter?
Widget not updating in flutter?

Time:05-25

This method is not updating the widget

Widget displayAppropriateWidget() {
if (isParsedCorrectly) {
  _widgetToDisplay = displaySecondHalf;
} else {
  _widgetToDisplay = displayFirstHalf;
}
setState(() {});
return _widgetToDisplay;

}

Even when the bool in other file and this file updates widget doesn't update. I can only see the changes only after I hot reload

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: const PreferredSize(
    preferredSize: Size.fromHeight(100),
    child: CustomAppBar("Sign-Up"),
  ),
  body: Align(
    alignment: Alignment.center,
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Padding(
          padding: EdgeInsets.only(top: 100, bottom: 5),
          child: Image.asset(
            'assets/images/college.png',
            width: 200,
            fit: BoxFit.cover,
          ),
        ),
        displayAppropriateWidget(),
      ],
    ),
  ),
);
 }
}

CodePudding user response:

You need to listen to the changes of that bool by injecting it into the Widget in some way. For example by:

  1. Passing it into the widget as an argument - which you can do if the bool is declared in a Widget higher up in the widget tree. Then you can call setState in that parent Widget once you've updated the bool. But setState can only be used in StatefulWidget. More on using setState here: https://docs.flutter.dev/development/ui/interactive and here: https://api.flutter.dev/flutter/widgets/State/setState.html
  2. Or by using some sort of state management. Here's a tutorial for that: https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

Also, your function displayAppropriateWidget calls setState, which you should not do from inside a Widgets build method - since that would mean rebuilding every time you build, causing infinite rebuilds.

Another tip is to try to avoid building Widgets from functions, as it's not as performant and can lead to some hard to identify bugs: https://www.youtube.com/watch?v=IOyq-eTRhvo

CodePudding user response:

Please refer to below example code of updating value from another class

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.

ValueNotifer & ValueListenableBuilder can be used to hold value and update widget by notifying its listeners and reducing number of times widget tree getting rebuilt.

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
final ValueNotifier<int> counter = ValueNotifier(0);

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

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

class FloatingActionButtonClass extends StatelessWidget {
  void _incrementCounter() {
    counter.value  ;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.

      body: Center(
        child: InkWell(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => MyHomePage()),
            );
          },
          child: Text("Floating Action Button"),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            ValueListenableBuilder(
              valueListenable: counter,
              builder: (context, value, child) {
                return Text(
                  counter.value.toString(),
                  style: Theme.of(context).textTheme.headline4,
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

  • Related