how to break code into small chunks to make the code cleaner in flutter

219 views Asked by At

I have a profile page where I am using PageController.

Now the form have 3 to 4 set of sections which I want to extract to different ( respective ) files.

Issue is if I do it via widget how Will I pass data. What I am using is methodBuilder way. is this right way to do it ?

code -> profile page body:

import 'package:flutter/material.dart';

import 'nick_name.dart';
import 'profile_form.dart';

class Body extends StatefulWidget {
  @override
  _BodyState createState() => _BodyState();
}

class _BodyState extends State<Body> {
  PageController _pageControler;
  String nickkname,
      firstName,
      middleName,
      lastName,
      gender,
      phoneNumber,
      panNumber;
  List<Widget> _pageList = [
    buildNickNameUI(),
    buildProfileFormUI(),
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      child: PageView(
        controller: _pageControler,
        scrollDirection: Axis.vertical,
        children: _pageList,
      ),
    );
  }
}


code: -> nickName page :

import 'package:flutter/material.dart';

Container buildNickNameUI() => Container(
      color: Colors.blue,
    );

code: -> profileForm page :

import 'package:flutter/material.dart';


Container buildProfileFormUI() => Container(
      color: Colors.red,
    );

is this the right way and follows best practice ?

1

There are 1 answers

2
Joseph Utulu On

You can create a separate dart file for each section and have something like this:

import 'package:flutter/material.dart'

class SectionName extends StatelessWidget {
    String arg1, arg2, arg3;

    SectionName(this.arg1, this.arg2, this.arg3) // Constructor with arguments

    @override
    Widget build(BuildContext context) {
        return Container(
            color: color
        );
    }
}

You can then import the individual files and use them in your pageView.