9.4 C
New York
Saturday, December 2, 2023

Flutter: Import only 1 class from a file contains multi classes

In Dart and Flutter, if you want to import only one class from a file that contains multiple classes, just use the show keyword.

Example

LetÂ’s say we have 2 files: main.dart and test.dart. The test.dart file has 2 classes named FirstClass and SecondClass but we only want to use FirstClass. Therefore, it makes sense if we just import FirstClass and ignore SecondClass as shown below:Advertisements

// main.dart
import './test.dart' show FirstClass;

HereÂ’s the code in the test.dart file:

import 'package:flutter/material.dart';

// FirstClass
class FirstClass extends StatelessWidget {
  const FirstClass({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.amber,
      child: const Center(
          child: Text(
        'First Class',
        style: TextStyle(fontSize: 40),
      )),
    );
  }
}

// SecondClass
class SecondClass extends StatelessWidget {
  const SecondClass({Key? key}) : super(key: key);

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

The full source code in main.dart:

// main.dart
import 'package:flutter/material.dart';

// import FirstClass 
import './test.dart' show FirstClass;

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the DEBUG banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('KindaCode.com')),
      body: const FirstClass(),
    );
  }
}

HereÂ’s the output:

AdvertisementsIf you try to call the SecondClass, you will face an error that looks like this:

ThatÂ’s it. Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles