3

I create a widget that have many part. So, it is not good practice to create this widget in one file. So that, I rearrange in many file. I make private these widgets(part), so that, these can't be accessed in other file. I want to access these widgets only in root widget.(or private classes can be accessed in its directory files) How can I do it?

// homepage/homepage.dart

import 'package:flutter/material.dart';

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          _Part1(),
          _Part2(),
        ],
      ),
    );
  }
}

// homepage/part1.dart
import 'package:flutter/material.dart';

class _Part1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}
// homepage/part2.dart
import 'package:flutter/material.dart';

class _Part2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}
Prantik
  • 67
  • 1
  • 4
  • 1
    It's not good practice to make widgets private as they are supposed to be reused throughout many screens. Although you can fix your issue with library and part, its still better to make the widgets public. – CoderUni Apr 03 '21 at 04:13

1 Answers1

8

Dart has functionality for part files. Though this isn't what I thought it'd be used for, it works here too. Simply do this:

// homepage/homepage.dart

import 'package:flutter/material.dart';

part 'part1.dart';
part 'part2.dart';

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          _Part1(),
          _Part2(),
        ],
      ),
    );
  }
}
// homepage/part1.dart
part of 'homepage.dart';

class _Part1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}
// homepage/part2.dart
part of 'homepage.dart';

class _Part2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

Part files are basically parts of the referred file, so it can access everything in the referred file and vice versa. If you need to import anything, you'll have to import them to the referred file as part files get imports from the referred file. Thus, you'll notice there is no import 'package:flutter/material.dart'; in the part files.

rkdupr0n
  • 691
  • 6
  • 18