Skip to main content

Flutter Render Widget From Another Class in Main Class

Flutter supports all the dynamic widget render methods like other mobile app development platforms. In today's tutorial we would call the Child widget directly from another class like a function and render it within our main App class. We can perform any task on the in the Sub class and it will automatically applied when we render the child class within our Root container.

Flutter Render Widget From Another Class in Main Class:

1. Defining a class RenderText with Statelesswidget. In this class we are rendering a Text widget. You can render any widget here.
class RenderText extends StatelessWidget {
  const RenderText({super.key});
  @override
  Widget build(BuildContext context) {
    return const Text(
      'Text Render From Outer Class',
      style: TextStyle(fontSize: 28, color: Colors.black),
      textAlign: TextAlign.center,
    );
  }
}
2. Defining our main Class App. In this class we are calling above RenderText class directly as a Child within the Center widget.
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: Scaffold(body: Center(child: RenderText())));
  }
}
Complete source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class RenderText extends StatelessWidget {
  const RenderText({super.key});
  @override
  Widget build(BuildContext context) {
    return const Text(
      'Text Render From Outer Class',
      style: TextStyle(fontSize: 28, color: Colors.black),
      textAlign: TextAlign.center,
    );
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: Scaffold(body: Center(child: RenderText())));
  }
}
Screenshot:
Flutter Render Widgets From Another Class in Main Class

Comments