How do add or remove a component from the layout in Flutter?

1,874

In Flutter, because widgets are immutable there is no direct equivalent to addChild(). Instead, you can pass a function to the parent that returns a widget, and control that child’s creation with a boolean flag.

For example, here is how you can toggle between two widgets when you click on a FloatingActionButton:

import 'package:flutter/material.dart';

void main() => runApp(SampleApp());

class SampleApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sample App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SampleAppPage(),
    );
  }
}

class SampleAppPage extends StatefulWidget {
  SampleAppPage({Key key}) : super(key: key);

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

class _SampleAppPageState extends State<SampleAppPage> {
  // Default value for toggle
  bool toggle = true;
  void _toggle() {
    setState(() {
      toggle = !toggle;
    });
  }

  _getToggleChild() {
    if (toggle) {
      return Container(
          width: 200,
          height: 40,
          color: Colors.amber,
          child: Center(child: Text('Tony Stark')));
    } else {
      return Container(
          width: 200,
          height: 40,
          color: Colors.grey.shade200,
          child: Center(
              child: TextField(
            autofocus: true,
            decoration: new InputDecoration(
                contentPadding:
                    EdgeInsets.only(left: 10, bottom: 11, top: 11, right: 15),
                hintText: "Edit name"),
          )));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Sample App"),
      ),
      body: Center(
        child: _getToggleChild(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _toggle,
        tooltip: 'Update Text',
        child: Icon(Icons.update),
      ),
    );
  }
}

enter image description here

Share:
1,874
Paresh Mangukiya
Author by

Paresh Mangukiya

I am a Mobile App Developer and Team Leader at BlueBit Technologies, in this My core competency lies in the complete end-to-end management and completing the entire project (iOS, Android and Backend side). I am seeking opportunities to build Mobile Apps from the ground up for you or your business. Please feel free to contact me here ⬇ Skype: pkmangukiya_1 Mobile or WhatsApp: +91 9723680658 Email: [email protected] I have spent 4+ years in the IT industry, I have developed a wide range of (iOS and Android) Applications using iOS (Swift, Objective-C), Flutter(Dart) and Android (Kotlin, Java). I work with B2B clients - Software companies and as well as B2C - Small and Medium Enterprises (SME) in many vertical industries and I passionate about good service &amp; deliver a high-quality product. I have experience in mobile Application Development, App principles, processes, theories and concepts. I am involved in the full life cycle of designing, developing, testing, Analysis, and maintaining applications. And I have also enough knowledge and experience of how to use and where to use Encryption, Exception Handling, Token-based Authentication and other security features in applications. My core competency lies in complete end-to-end management of new Mobile Applications and I am seeking opportunities to build Mobile Apps from the ground up for you or your business. My experience has been awesome and good so far, I have learned a lot of new things and worked during this time. My years of experience have prepared me well for this position. Skills: Programming Languages: iOS: Swift and Objective C Flutter: Dart Android: Java and Kotlin C/C++ Professional Experience: Socket Programming DB &amp; API Design Google API, Facebook API, Google Maps and Direction, Location Services Integrating ads ( Google Ads, Admob, Facebook Ads), Media Player Functionalities API security with JWT JSON, XML In-app purchase User Authentication Chat and Messaging Hosting (App Store, Play Store) Payment Gateways Social Media Integration SQLite Database, Firebase Database, MySQL Database Advanced Analytics Mobile Application Design Document Conversion Projects Variations: Chatting and Messaging: Text and Voice messaging, video communication, photo &amp; video sharing Loan Management System Online Music Streaming QR &amp; Barcode Scanner Parking Facility Social Media: Professional networks, social networks and Data Sharing Lifestyle: Religion, travel, blogs, fashion, health, fitness Music + Audio Video Mixer with dynamic features Football Training Club and Academy Photo and Video Editor App Organization Management Society management Quiz - Play &amp; Win I really enjoy programming a lot!

Updated on December 26, 2022

Comments

  • Paresh Mangukiya
    Paresh Mangukiya over 1 year

    How can add and remove any widget such as Container or Text from the Flutter app? like on the screen where you press any button and it adds or deletes components which consist of ViewItems and Edititems widgets.

    Do it In Android, you call addChild() or removeChild() on a parent to dynamically add or remove child views. So is there some way like this in a Flutter?

    How can we add & remove a widget from a layout in a flutter?