Replace widgets like fragments in Flutter

flutter fragment activity
flutter navigation drawer with fragments
flutter fragment tutorial
fragment example in flutter
flutter widgets
fragment stack in flutter
flutter change widget on click
how to use flutter in android

I'm new to Flutter.

I have an app with 2 sub widgets (2 fragments in Android), and when i clicked next button in WidgetA, I want to replace (or push) that widget into WidgetChildA, like push (or replace) fragments in Android. But instead of that, I got a fullscreen widget like a normal screen in Flutter.

Here is my code:

import 'package:flutter/material.dart';

class DemoFragment extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new DemoFragmentState();
  }
}

class DemoFragmentState extends State<DemoFragment> {
  @override
  Widget build(BuildContext context) {
    print(context.toString() + context.hashCode.toString());
    return new Scaffold(
      appBar: new AppBar(title: new Text("Demo fragment")),
      body: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          new FragmentA(),
          new FragmentB()
        ],
      ),
    );
  }
}

class FragmentA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print(context.toString() + context.hashCode.toString());
    return new Center(
      child: new Column(
        children: <Widget>[
          new Text("Fragment A"),
          new RaisedButton(
              child: new Text("next"),
              onPressed: () {
                print(context.toString() + context.hashCode.toString());
                Navigator.of(context).push(new PageRouteBuilder(
                    opaque: true,
                    transitionDuration: const Duration(milliseconds: 0),
                    pageBuilder: (BuildContext context, _, __) {
                      return new FragmentChildA();
                    }));

                /*showDialog(
                    context: context,
                    builder: (_) => new AlertDialog(
                          title: new Text("Hello world"),
                          content: new Text("this is my content"),
                        ));*/
              })
        ],
      ),
    );
  }
}

class FragmentB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print(context.toString() + context.hashCode.toString());
    return new Center(
        child: new Column(
      children: <Widget>[
        new Text("Fragment B"),
        new RaisedButton(
            child: new Text("next"),
            onPressed: () {
              print(context.toString() + context.hashCode.toString());
              Navigator.of(context).push(new PageRouteBuilder(
                  opaque: true,
                  transitionDuration: const Duration(milliseconds: 0),
                  pageBuilder: (BuildContext context, _, __) {
                    return new FragmentChildB();
                  }));
            })
      ],
    ));
  }
}

class FragmentChildA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: new Center(
            child: new Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[new Text("Fragment Child A")],
    )));
  }
}

class FragmentChildB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: new Center(
            child: new Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[new Text("Fragment Child B")],
    )));
  }
}

Screenshots:

Home page

After clicked

I'm not sure if you can use the router to replace just the part of a view; but you could conditionally change which Widget you render in the build method, like this:

children: <Widget>[
    someCondition ? new FragmentA() : new FragmentChildA(),
    new FragmentB()
],

Then you just need to set someCondition by using setState in the stateful widget:

setState(() => someCondition = true);

If you want to do this from inside FragmentA you could allow it to have the function passed into its constructor:

new FragmentA(
  onPress: setState(() => someCondition = true)
)

However, it might be better to encapsulate all of this logic inside a single widget so this logic isn't all hanging around in the parent. You could make a single StatefulWidget for FragementA which keeps track of which stage you're on, and then in its build method renders the correct child widget, something like:

build() {
  switch(stage) {
    Stages.Stage1:
      return new Stage1(
        onNext: () => setState(() => stage = Stages.Stage2);
      );
    Stages.Stage2:
      return new Stage1(
        onPrevious: () => setState(() => stage = Stages.Stage1);
      );
  }
}

Flutter: Setting up a Navigation Drawer with Multiple Fragments , Flutter: Setting up a Navigation Drawer with Multiple Fragments (Widgets) to the term fragment, lets call each section or the widget you want to show as a fragment. This widget is used to replace the existing widget in body: of the Scaffold. How to replace widgets like fragments in flutter. You could simply use a MaterialApp widget with the CupertinoPageTransitionsBuilder as pageTransitionTheme How to replace widgets like fragments in flutter. You could simply use a MaterialApp widget with the CupertinoPageTransitionsBuilder as pageTransitionTheme

ok I'm going to be doing this the same way google does it with the bottom navigation bar, I don't see this as the most performant but it works

  class MainFabContainer extends StatefulWidget {

    MainFabContainer({
      Key key,
    }) : super(key: key);

    @override
    State<StatefulWidget> createState() {
      return MainFabContainerState();
    }

  }

  class MainFabContainerState extends State<MainFabContainer> {
    String title = "Title";
    int _currentIndex = 0;
    final List<int> _backstack = [0];

    @override
    Widget build(BuildContext context) {
      //each fragment is just a widget which we pass the navigate function
      List<Widget> _fragments =[Fragment1(navigate: navigateTo),Fragment2(navigate: navigateTo,),Fragment3(navigate: navigateTo,)];
      //will pop scope catches the back button presses
      return WillPopScope(
        onWillPop: () {
          customPop(context);
        },
        child: Scaffold(
          drawer: drawer(),
          appBar: AppBar(
            title: Text(title),
          ),
          body: Column(
            children: <Widget>[
              Expanded(
                child: _fragments[_currentIndex],
              ),
            ],
          ),
        ),
      );
    }


    void navigateTo(int index) {
      _backstack.add(index);
      setState(() {
        _currentIndex = index;
      });
    }

    void navigateBack(int index) {
      setState(() {
        _currentIndex = index;
      });
    }

    customPop(BuildContext context) {
      if (_backstack.length - 1  > 0) {
        navigateBack(_backstack[_backstack.length - 1]);
      } else {
        _backstack.removeAt(_backstack.length - 1);
        Navigator.pop(context);
      }
    }
    //this method could be called by the navigate and navigate back methods
    _setTitle(String appBarTitle) {
      setState(() {
        title = appBarTitle;
      });
    }
  }

Replace widgets like fragments in Flutter, I'm new to Flutter. I have an app with 2 sub widgets (2 fragments in Android), and when i clicked next button in WidgetA, I want to replace (or push) that widget  The flutter BottomNavigationBar tutorial describes how to replace image widgets using the BottomNavigationBar widget. The BottomNavigationBar is displayed above the navigation icons for an Android device. The BottomNavigationBar’s index is used for updating the BottomNavigationBar from either the popup menu or drawer.

You could simply use a MaterialApp widget with the CupertinoPageTransitionsBuilder as pageTransitionTheme like

MaterialApp(
   theme: ThemeData(
   pageTransitionsTheme: PageTransitionsTheme(builders: {
   TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
   TargetPlatform.android: SlideRightPageTransitionsBuilder(),
   }),
   initialRoute: "fragment1",
   routes: <String, WidgetBuilder>{
      "fragment1": (BuildContext context) => Fragment1(),
      "fragment2": (BuildContext context) => Fragment2(),
   }
...
),

Then in fragment 1 you simply use the following to navigate to the other fragment with a slide animation

Navigator.of(context).pushReplacementNamed("fragment2");

fragment, fragment 0.3.1. Published May 9, 2019. 1 like. flutter android ios web. Readme import 'package:fragment/fragment.dart'; // Create Widget like before class  _getDrawerItemWidget(int pos) will simply return a new widget of any type based on the selected drawer item. This widget is used to replace the existing widget in body: of the Scaffold.

Well, I found out the way to handle this case for a few months, but I just forgot to answer this question.

The solution is wrapping your Widget with a new Navigator.

You can see the video example here

And the simple demo for it here

The downside of this solution is sometimes, the keyboard is not showing as my intention.

Flutter for Android developers, Learn how to add a Flutter Fragment to your existing Android app. Introduction to widgets · Building layouts Somewhere in your app, before your FlutterFragment is needed, like in the // Application class . those displays need to setup a method channel and explicitly instruct their Dart code to change Navigator routes. Every widget in Flutter is by nature, reusable. Every widget in Flutter is like a Fragment. All we need to do is define two widgets. One for the master list, one for the detail view. These are, in

Adding a Flutter Fragment to an Android app, In the tutorial, you are just changing the displayed widget rather than pushing a new Each fragment is a .dart file which is devided like this :. Create beautiful apps faster with Flutter’s collection of visual, structural, platform, and interactive widgets. In addition to browsing widgets by category, you can also see all the widgets in the widget index. Make your app accessible. Bring animations to your app. Manage assets, display images, and show icons.

Change fragment from current fragment - General , How to replace widgets like fragments in flutter. You could simply use a MaterialApp widget with the CupertinoPageTransitionsBuilder as  Flutter widgets are built using a modern framework that takes inspiration from React. The central idea is that you build your UI out of widgets. Widgets describe what their view should look like given their current configuration and state. When a widget’s state changes, the widget rebuilds its description, which the framework diffs against

How to replace widgets like fragments in flutter?, Flutter makes it easy and fast to build beautiful apps for mobile and beyond. These details WILL change. Many Android apps achieve navigation by switching out different Fragment s as "screens" within a single Activity . Use Flexible for resizing your widgets in rows and columns. You can use it to adjust how much space different child widgets take up relative to their parent widgets. Learn more about Flexible

Comments
  • Where you want to replace? You want to replace the button with your fragment?
  • I want to replace FragmentA to FragmentChildA
  • im looking to do this too, ive got a few ideas, i dont really want the entire thing to be stateful and swap the widget on a conditional, i wonder how the bottom navigation view does it, do you have any update on this
  • @ChâuMinhPhúc could you resolve your problem?
  • @ChâuMinhPhúc Did you find a solution?
  • yeah, I understood this state concept of Flutter, but I wonder if there is a way similar to Android.
  • I'm not familiar with Android dev, so not sure how it works there, but I don't think you can just replace a part of a widget in Flutter, because when the parent build method is called, it's just going to create the old widget again.
  • @Danny Tuppeny could you help me on this topic? https://stackoverflow.com/q/56223550/1830228
  • whats navigateTo in fragment parameters and when i press back button i get Unhandled Exception: Scaffold.geometryOf() must only be accessed during the paint phase. error
  • its in my answer, and your error sounds like your trying to change the wrong widget
  • could you say whats navigateTo parameters in fragment parameters? and how about using them
  • its in the answer i think you need to scroll the answer it shows 2 methods navigateTo and navigateBack void navigateTo(int index) { _backstack.add(index); setState(() { _currentIndex = index; }); } void navigateBack(int index) { setState(() { _currentIndex = index; }); }
  • yes i know that, please let me to create new issue and link you that, thanks