EN VI

Flutter - How to update a scaffold is body content?

2024-03-16 22:00:06
Flutter - How to update a scaffold is body content?

I am developing a Flutter / Dart mobile app for Android, and I am having a problem with changing a page's body.

I have a Scaffold widget at the top, including a Floating action button and BottomNavBar. For the body I have a Pageview widget that allows me to swipe between the various pages of the bottomNavBar. This works fine.

For the first page, it is defined as follows:

children: <Widget>[
          //--------- Read page
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: readPage,
          ), //Padding

readPage is a widget variable defined as follows:

@override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    Widget readPage = BeforeRead(theme: theme);

    return Scaffold(

So this widget is defined as a page, kind of like a starting point. My floating action button is defined as follows:

floatingActionButton: FloatingActionButton(
        onPressed: () {
          //used to change readPage variable
          setState(() {
            readPage = AfterRead(theme: theme);
          });
        },
        child: const Icon(Icons.nfc),
      ),

So, The floating action button is supposed to change the content of this readPage variable and update the page using setState(). However, it does not work.

What am I doing wrong here?

Here is the full code of the app

Some visual aid, here is the app's appearance: Yes, the app is in Portuguese, sorry about that

The only purpose of the button is to simulate me leaning an NFC tag into the smartphone, since the NFC part of the project is not yet done.

Solution:

Your page must be a StatefulWidget for this and you must define readPage in the State:

class _MyPageState extends State<MyPage>{
 Widget readPage = BeforeRead(theme: theme);

 @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);

    return Scaffold(

Your current approach doesn't work because your readPage variable is local and is redefined on every build, which overwrites your previous changes.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login