Access private class or function from other file in flutter

3.6k Views Asked by At

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(
      
    );
  }
}
1

There are 1 best solutions below

6
On

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.