Split Your Widgets in Flutter

Why?

Google’s Flutter is a framework that allows you to create a UI as code, with each building block called a widget, resulting in a widget tree. Any software developer should be concerned with making this tree readable and maintainable.

How?

Splitting an app into widgets is the process of dividing large widgets into smaller, more manageable widgets, which can be interpreted as smaller chunks of code. The key here is to understand when to divide a widget into smaller ones.

In this example I am gonna show demonstrate how I’m going to split my code:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({ Key? key }) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int currentIndex = 0; 

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("My First App"),
          backgroundColor: const Color(0xFFfb8b04),
        ),
        body: Center(
          child: Image.asset("images/WelcomeImage.png"),
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: const [
            BottomNavigationBarItem(
              label: "Home",
              icon: Icon(Icons.home),
            ),
            BottomNavigationBarItem(
              label: "Settings",
              icon: Icon(Icons.settings),
            )
          ],
          currentIndex: currentIndex, 
          onTap: (int index) { 
            setState(() {
              currentIndex = index;
            });
          },
        ),
      ),
    );
  }
}

Visual Studio Code Neat Feature

In my widgets I am going to use VSCode neat features to split my widgets I’ve shown above.

First, I want to split the code of my widget image in the body of my widget tree. So I am going to highlight it on VSCode and Right-Click > Refactor > Extract Widget then I’ll give it a name “BodyImageWidget” and the result will give this new block of widget.

Conclusion

So that’s it! Because of VSCode helpful feature “Extract Widget” that’s how easy it is to break our widget tree into smaller chunks which will make our widget tree easy to read and maintainable in the future while we make changes in the code.

Thank you for reading!

Sources:
https://www.geeksforgeeks.org/flutter-splitting-app-into-widgets/
https://medium.com/@JalalOkbi/flutter-widget-tree-split-the-ugly-the-bad-and-the-good-ce793199c4bb

Leave a Comment

Your email address will not be published. Required fields are marked *